pandas库操作
1、首先导入pandas库,一般都会用到numpy库,所以我们先导入备用:
import numpy as np
import pandas as pd
- 1
- 2
df = pd.DataFrame(pd.read_csv('name.csv',header=1))
df = pd.DataFrame(pd.read_excel('name.xlsx'))
- 1
- 2
df = pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006],
"date":pd.date_range('20130102', periods=6),
"city":['Beijing ', 'SH', ' guangzhou ', 'Shenzhen', 'shanghai', 'BEIJING '],
"age":[23,44,54,32,34,32],
"category":['100-A','100-B','110-A','110-C','210-A','130-F'],
"price":[1200,np.nan,2133,5433,np.nan,4432]},
columns =['id','date','city','category','age','price'])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
df.shape
- 1
df.info()
- 1
df.dtypes
- 1
df['B'].dtype
- 1
df.isnull()
- 1
df.isnull()
- 1
df['B'].unique()
- 1
df.columns
- 1
df.head() #默认前10行数据
df.tail() #默认后10 行数据
- 1
- 2
df.fillna(value=0)
- 1
df['prince'].fillna(df['prince'].mean())
- 1
df['city']=df['city'].map(str.strip)
- 1
df['city']=df['city'].str.lower()
- 1
df['price'].astype('int')
- 1
df.rename(columns={'category': 'category-size'})
- 1
df['city'].drop_duplicates()
- 1
df['city'].drop_duplicates(keep='last')
- 1
df['city'].replace('sh', 'shanghai')
- 1
df1=pd.DataFrame({"id":[1001,1002,1003,1004,1005,1006,1007,1008],
"gender":['male','female','male','female','male','female','male','female'],
"pay":['Y','N','Y','Y','N','Y','N','Y',],
"m-point":[10,12,20,40,40,40,30,20]})
- 1
- 2
- 3
- 4
df_inner=pd.merge(df,df1,how='inner') # 匹配合并,交集
df_left=pd.merge(df,df1,how='left') #
df_right=pd.merge(df,df1,how='right')
df_outer=pd.merge(df,df1,how='outer') #并集
- 1
- 2
- 3
- 4
df_inner.set_index('id')
- 1
df_inner.sort_values(by=['age'])
- 1
df_inner.sort_index()
- 1
df_inner['group'] = np.where(df_inner['price'] > 3000,'high','low')
- 1
df_inner.loc[(df_inner['city'] == 'beijing') & (df_inner['price'] >= 4000), 'sign']=1
- 1
pd.DataFrame((x.split('-') for x in df_inner['category']),index=df_inner.index,columns=['category','size']))
- 1
df_inner=pd.merge(df_inner,split,right_index=True, left_index=True)
- 1
df_inner.loc[3]
- 1
df_inner.iloc[0:5]
- 1
df_inner.reset_index()
- 1
df_inner=df_inner.set_index('date')
- 1
df_inner[:'2013-01-04']
- 1
df_inner.iloc[:3,:2] #冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。
- 1
df_inner.iloc[[0,2,5],[4,5]] #提取第0、2、5行,4、5列
- 1
df_inner.ix[:'2013-01-03',:4] #2013-01-03号之前,前四列数据
- 1
df_inner['city'].isin(['beijing'])
- 1
df_inner.loc[df_inner['city'].isin(['beijing','shanghai'])]
- 1
pd.DataFrame(category.str[:3])
- 1
df_inner.loc[(df_inner['age'] > 25) & (df_inner['city'] == 'beijing'), ['id','city','age','category','gender']]
- 1
df_inner.loc[(df_inner['age'] > 25) | (df_inner['city'] == 'beijing'), ['id','city','age','category','gender']].sort(['age'])
- 1
df_inner.loc[(df_inner['city'] != 'beijing'), ['id','city','age','category','gender']].sort(['id'])
- 1
df_inner.loc[(df_inner['city'] != 'beijing'), ['id','city','age','category','gender']].sort(['id']).city.count()
- 1
df_inner.query('city == ["beijing", "shanghai"]')
- 1
df_inner.query('city == ["beijing", "shanghai"]').price.sum()
- 1
df_inner.groupby('city').count()
- 1
df_inner.groupby('city')['id'].count()
- 1
df_inner.groupby(['city','size'])['id'].count()
- 1
df_inner.groupby('city')['price'].agg([len,np.sum, np.mean])
- 1
df_inner.sample(n=3)
- 1
weights = [0, 0, 0, 0, 0.5, 0.5]
df_inner.sample(n=2, weights=weights)
- 1
- 2
df_inner.sample(n=6, replace=False)
- 1
df_inner.sample(n=6, replace=True)
- 1
df_inner.describe().round(2).T #round函数设置显示小数位,T表示转置
- 1
df_inner['price'].std()
- 1
df_inner['price'].cov(df_inner['m-point'])
- 1
df_inner.cov()
- 1
df_inner['price'].corr(df_inner['m-point']) #相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关
- 1
df_inner.corr()
- 1
df_inner.to_excel('excel_to_python.xlsx', sheet_name='bluewhale_cc')
- 1
df_inner.to_csv('excel_to_python.csv')
转自:https://blog.csdn.net/liufang0001/article/details/77856255