pandas 使用技巧
pandas 使用技巧
pandas是用到numpy构建的高性能数据统计库。提供了Series 、DataFrame 、 Panel三种结构
可以认为是Series为一维,DataFrame 二维,Panel 维三维
1.Series
引入包维import pandas as pd
建立Series对象,会有默认的s索引,从0 开始;
建立字母索引
2.DataFrame
2.1创建
>>>datas=pd.date_range('20200325',periods=10)
>>>print(datas)
DatetimeIndex(['2020-03-25', '2020-03-26', '2020-03-27', '2020-03-28',
'2020-03-29', '2020-03-30', '2020-03-31', '2020-04-01',
'2020-04-02', '2020-04-03'],
dtype='datetime64[ns]', freq='D')
2.2df的行列转化 T
2.3数据选择
1)创建5*3的数据
>>>df = pd.DataFrame(np.random.randn(5,3),index=['a','b','c','d','e'],columns=['item1','item2','item3'])
df
item1 item2 item3
a 0.676389 1.341308 1.645973
b 0.508344 -0.925485 -0.646946
c -0.023020 -0.303764 -1.319574
d 0.814602 0.470118 0.026144
e -0.349248 0.582652 -0.812306
2)选择item2列的数据
3)选择一行的数据 c行,也就是第三行的数据
df.loc["c"]
item1 -0.023020
item2 -0.303764
item3 -1.319574
Name: c, dtype: float64
2.4 处理缺少的数据 Nan 也就是空值
df = pd.DataFrame(np.random.randn(5,3),index=['a','b','c','d','e'],columns=['item1','item2','item3'])
df1=df.reindex(index=['a','b','c','d','e'],columns=['item1','item2','item3','item4'])
df1
item1 item2 item3 item4
a -1.267918 0.041318 0.451010 NaN
b 0.228371 0.132116 0.150561 NaN
c 1.334173 0.906305 -1.549433 NaN
d 0.524939 0.023399 0.463487 NaN
e 0.859803 -0.381741 1.077619 NaN
df1.iat[0,3]=0.0099 #增加item4列的第一个位0.0099数据
df1 #查看df1还有Nan的情况
item1 item2 item3 item4
a -1.267918 0.041318 0.451010 0.0099
b 0.228371 0.132116 0.150561 NaN
c 1.334173 0.906305 -1.549433 NaN
d 0.524939 0.023399 0.463487 NaN
e 0.859803 -0.381741 1.077619 NaN
#过滤掉Nan的命令
>>>df1.dropna(how='any')
item1 item2 item3 item4
a -1.267918 0.041318 0.45101 0.0099
#填充Nan的值为0.8888
2.5 统计和汇总
#用到系统的describe()函数
2.6 时间序列
按照每一天
index=pd.date_range('2020-1-1',periods=5)
print(index)
DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
'2020-01-05'],
dtype='datetime64[ns]', freq='D')
按照每个月
index=pd.date_range('2020-1-1',periods=12,freq='M')
print(index)
DatetimeIndex(['2020-01-31', '2020-02-29', '2020-03-31', '2020-04-30',
'2020-05-31', '2020-06-30', '2020-07-31', '2020-08-31',
'2020-09-30', '2020-10-31', '2020-11-30', '2020-12-31'],
dtype='datetime64[ns]', freq='M')
假设12各个月的0,500的随机数据为
ts=pd.Series(np.random.randint(0,500,len(index)),index=index)
print(ts)
2020-01-31 472
2020-02-29 90
2020-03-31 322
2020-04-30 111
2020-05-31 391
2020-06-30 395
2020-07-31 257
2020-08-31 137
2020-09-30 154
2020-10-31 315
2020-11-30 277
2020-12-31 239
1) 标准统计
ts.describe()
count 12.000000
mean 263.333333
std 122.574900
min 90.000000
25% 149.750000
50% 267.000000
75% 339.250000
max 472.000000
dtype: float64
2)统计每3各个月的汇总值
3) 统计每2个月的汇总值
4)半年的汇总值
2.7 文件I/o
可以通过文件I/O函数,将数据多种形式保存到文件中,csv,execl,json等
保存文件:df.csv