python_pandasDAY_19(2)数据IO

学习内容
pandas数据操作
重点
1.csv数据的读入

import pandas as pd
import numpy as np

print(pd.read_csv("data1.csv"))#直接读取csv文件
       a b c d
0      1 2 3 4
1  11 12 13 14
#这么看来我们发现数据貌似不对行



print(pd.read_csv("data1.csv", header=None, names=["one", 'two', 'three', 'four']))
#指定列索引读取数据,让数据更规整
           one  two  three  four
0      a b c d  NaN    NaN   NaN
1      1 2 3 4  NaN    NaN   NaN
2  11 12 13 14  NaN    NaN   NaN
#但是我们发现数据全部并入one这一列,并不是我们所想要的



print(pd.read_csv("data1.csv", sep="\s+", header=None, 
names=["one", 'two', 'three', 'four']))
#引入正则表达式,\s+表示检索空格或多个空格为分隔符
  one two three four
0   a   b     c    d
1   1   2     3    4
2  11  12    13   14
#这样数据就对整齐了



print(pd.read_csv("data1.csv", sep='\s+', header=None, 
names=["one", 'two', 'three', 'four'],index_col='one'))
#在上述基础上,我们可以指定关键字作为分组
    two three four
one               
a     b     c    d
1     2     3    4
11   12    13   14
#完美处理数据




print(pd.read_csv("data1.csv", sep="\s+", header=None, 
names=["one", 'two', 'three', 'four'],na_values=["d",2,11]))
#在此基础上我们可以指定位置内容为空
   one  two three  four
0    a    b     c   NaN
1    1  NaN     3   4.0
2  NaN   12    13  14.0
#这样对应位置就变成NAN




print(pd.read_csv("data1.csv", sep="\s+", header=None,
 names=["one", 'two', 'three', 'four'],
 na_values={"one":["d",2],"two":["d",11],"four":[2,11]}))
 #在上述基础上,我们可以精确到指定列的具体值为空
   one two three four
0   a   b     c    d
1   1   2     3    4
2  11  12    13   14
#one没有d和2,所以没有值为空,其他也是同理



print(pd.read_csv("data1.csv", sep="\s+", header=None, 
names=["one", 'two', 'three', 'four'],nrows=2))
#只读两行
  one two three four
0   a   b     c    d
1   1   2     3    4

超大数据处理
有时候我们所要处理的数据可能成千上亿行,这时候就需要用到chunksize来读取一定数据

import pandas as  pd
s=pd.read_csv("data2.csv",chunksize=1000)
print(s)#读取数据的前1000行
#这个时候s就成了可迭代对象,支持python的循环
#我们如果要统计数据的具体列出现相同内容的次数,就可以结合for循环
<pandas.io.parsers.TextFileReader object at 0x000001126C1B6978>




import pandas as pd
import chunk

s = pd.read_csv("data2.csv", chunksize=1000)
result = pd.Series([])
for m in s:
    result = result.add(chunk['key'].value_counts(), fill_value=0)
print(result[:10])
#这样就可以统计前1000行,列表签key所重复出现内容的次数,并打印前10个

3.文件写入磁盘

import pandas as pd
import chunk

s = pd.read_csv("data1.csv", sep="\s+",header=None)
print(s)
    0   1   2   3
0   a   b   c   d
1   1   2   3   4
2  11  12  13  14
s.to_csv("data1-1.csv")
#这个时候文件右侧栏就会找到data1-1的文件,这时候打开文件
,0,1,2,3
0,a,b,c,d
1,1,2,3,4
2,11,12,13,14
#再打开源文件
a b c d
1 2 3 4
11 12 13 14
#相比较,我们发现,由于加上了索引导致内容会有偏差
s.to_csv("data1-1.csv",index=False,header=None)
#这样就忽略掉索引,内容于data1一样了


s.to_csv("data1-1.csv",index=False,header=None,columns=[1,3])
#这样虽然忽略了索引,但是存入时只存列索引为1,3的内容
b,d
2,4
12,14
s.to_csv("data1-1.csv",index=False,header=None,columns=[1,3],sep=",")
#通过sep加入分隔符

二进制文件的操作
用pickle包进行处理,这里不在叙述

发布了41 篇原创文章 · 获赞 1 · 访问量 930

猜你喜欢

转载自blog.csdn.net/soulproficiency/article/details/104094140