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? ↩︎

posted @ 2019-03-03 20:47  Michael翔  阅读(1775)  评论(0编辑  收藏  举报