Python 處理 CSV/EXCEL 表格文件


只想說,數據挖掘工作,80%時間都花在處理數據上了,這句話真不假!

最近和小伙伴組了個隊參加數據分析比賽,記錄下我處理 csv 文件的一些步驟吧:

修改csv文件

可以用csv模塊[1],官方文檔[2]

import pandas as pd
import csv
city_class={1:['北京','上海','重慶','天津'],2:['成都','大連','沈陽'],3:['長春']}
with open('city_test.csv','r+') as f:
    f.readline()
    data=csv.reader(f)
    rows=[r for r in data]
    print(rows)
    for i in rows:
        for key,values in  city_class.items():
            if i[0] in values:
                i[0]=key
    writer = csv.writer(open('output.csv', 'w'))
    print(rows)
    writer.writerows(rows)                

修改excel

csv文件問題多多,不如直接用exel的xlsx文件也ok:

data = pd.read_excel('test.xlsx')
data['city'].map(dict)

這里使用map[3]對中文數據的城市進行匹配,替換成數字。

將excel文件中轉換成dict

a=df.set_index('city')['num'].to_dict()

將excel中的兩列轉換成字典,用來匹配我上面的城市。[4]

統計excel文件行數和列數

rows=len(data.index)
rows=data['某列名'].count()
data.shape()	#獲得形狀,是一個tuple   行數*列數

EDIT: As noted @Dan Allen in the comments len(df.index) and df[0].count() are not interchangeable as count excludes NaNs,[5]

統計計數

計數統計我們使用:value_counts()

參考


  1. 官方-CSV File Reading and Writing ↩︎

  2. so-python修改csv specific values ↩︎

  3. index-pandas-map ↩︎

  4. so-python pandas dataframe to dictionary ↩︎

  5. so-how to get row count of pandas dataframe? ↩︎


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM