各位读者朋友们,由于更新blog不易,如果觉得这篇blog对你有用的话,麻烦关注,点赞,收藏一下哈,十分感谢。
import numpy as np
import pandas as pd
df = pd.DataFrame(pd.read_csv('name.csv',header=1))
df = pd.DataFrame(pd.read_excel('name.xlsx'))
或者
import pandas as pd
from collections import namedtuple
Item = namedtuple('Item', 'reply pv')
items = []
with codecs.open('reply.pv.07', 'r', 'utf-8') as f:
for line in f:
line_split = line.strip().split('\t')
items.append(Item(line_split[0].strip(), line_split[1].strip()))
df = pd.DataFrame.from_records(items, columns=['reply', 'pv'])
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'])
df.shape
df.info()
df.dtypes
df['B'].dtype
df.isnull()
df['B'].isnull()
df['B'].unique()
df.values
df.columns
df.head() #默认前5行数据
df.tail() #默认后5行数据
df.fillna(value=0)
df['prince'].fillna(df['prince'].mean())
df['city']=df['city'].map(str.strip)
df['city']=df['city'].str.lower()
df['price'].astype('int')
df.rename(columns={'category': 'category-size'})
df['city'].drop_duplicates()
df['city'].drop_duplicates(keep='last')
df['city'].replace('sh', 'shanghai')
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]})
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') #并集
result = df1.append(df2)
result = left.join(right, on='key')
pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False,
keys=None, levels=None, names=None, verify_integrity=False,
copy=True)
例子:1.frames = [df1, df2, df3]
2.result = pd.concat(frames)
df_inner.set_index('id')
df_inner.sort_values(by=['age'])
df_inner.sort_index()
df_inner['group'] = np.where(df_inner['price'] > 3000,'high','low')
df_inner.loc[(df_inner['city'] == 'beijing') & (df_inner['price'] >= 4000), 'sign']=1
pd.DataFrame((x.split('-') for x in df_inner['category']),index=df_inner.index,columns=['category','size'])
df_inner=pd.merge(df_inner,split,right_index=True, left_index=True)
主要用到的三个函数:loc,iloc和ix,loc函数按标签值进行提取,iloc按位置进行提取,ix可以同时按标签和位置进行提取。
df_inner.loc[3]
df_inner.iloc[0:5]
df_inner.reset_index()
df_inner=df_inner.set_index('date')
df_inner[:'2013-01-04']
df_inner.iloc[:3,:2] #冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。
df_inner.iloc[[0,2,5],[4,5]] #提取第0、2、5行,4、5列
df_inner.ix[:'2013-01-03',:4] #2013-01-03号之前,前四列数据
df_inner['city'].isin(['beijing'])
df_inner.loc[df_inner['city'].isin(['beijing','shanghai'])]
pd.DataFrame(df_inner['category'].str[:3])
使用与、或、非三个条件配合大于、小于、等于对数据进行筛选,并进行计数和求和。
df_inner.loc[(df_inner['age'] > 25) & (df_inner['city'] == 'beijing'), ['id','city','age','category','gender']]
df_inner.loc[(df_inner['age'] > 25) | (df_inner['city'] == 'beijing'), ['id','city','age','category','gender']].sort(['age'])
df_inner.loc[(df_inner['city'] != 'beijing'), ['id','city','age','category','gender']].sort(['id'])
df_inner.loc[(df_inner['city'] != 'beijing'), ['id','city','age','category','gender']].sort(['id']).city.count()
df_inner.query('city == ["beijing", "shanghai"]')
df_inner.query('city == ["beijing", "shanghai"]').price.sum()
主要函数是groupby和pivote_table
df_inner.groupby('city').count()
df_inner.groupby('city')['id'].count()
df_inner.groupby(['city','size'])['id'].count()
df_inner.groupby('city')['price'].agg([len,np.sum, np.mean])
数据采样,计算标准差,协方差和相关系数
df_inner.sample(n=3)
weights = [0, 0, 0, 0, 0.5, 0.5]
df_inner.sample(n=2, weights=weights)
df_inner.sample(n=6, replace=False)
df_inner.sample(n=6, replace=True)
df_inner.describe().round(2).T #round函数设置显示小数位,T表示转置
df_inner['price'].std()
df_inner['price'].cov(df_inner['m-point'])
df_inner.cov()
df_inner['price'].corr(df_inner['m-point']) #相关系数在-1到1之间,接近1为正相关,接近-1为负相关,0为不相关
df_inner.corr()
分析后的数据可以输出为xlsx格式和csv格式
df_inner.to_excel('excel_to_python.xlsx', sheet_name='bluewhale_cc')
df_inner.to_csv('excel_to_python.csv')