干货 | pandas常用技巧笔记

mac2024-05-15  29

下面以代码+注释的形式进行记录

# 为模块添加别名 import pandas as pd # 创建DataFrame df = pd.read_csv('RFM_TRAD_FLOW.csv',encoding = 'gbk') df = pd.DataFrame(columns = ['transID', 'cumid', 'time', 'amount', 'type_label', 'type']) df.head(5) # loc是实际序列,比如第一行,第一列 # iloc是按照定义好的行列名 # ix是loc+iloc # 对DataFrame进行数据操作 # 添加一列 df['col1_new'] = df['type'] # 添加一行 df.loc['row_new'] = df.loc[2,:] # 给某一列/行数据+1 df['transID'] = df['transID'].map(lambda x: x+1) # 判断数据并添加数据到新DataFrame里 for i in range(df.iloc[:,0].size): if df.loc[i,'type'] == 'returned_goods': # 注意这里必须是loc,否则会报错,原因的话可分别列数据查证 df1.loc[i] = df.loc[i] # 重置序列,改为0,1,2... df = df.reset_index(drop=True, inplace=True) # 某列值的频次,频率 # 检查频数 df['type'].value_counts() # 检查频率 df['type'].value_counts(normalize = True)

1.pandas 读写excel,csv,json等见另一篇博文:传送门

2.shift + Tab 可查看函数具体使用方法

3.在jupyter notebook里可以不同窗格写脚本,方便调试和查看

4.pandas的多表联合拼接merge

import pandas as pd # 读取第一个文件转成DataFrame df1 = pd.read_excel('test1.xlsx') # 读取第二个文件转成DataFrame df2 = pd.read_excel('test2.xlsx') ''' df2:是你要merge的对象 how:是连接方式,分为[inner,outer,left,right]与sql类似 on:是两者需要连接的列,如果是多列,加列表来写入 left_on,right_on:是指定左/右边的DataFrame以哪个列名或者索引名进行连接,如果前面on写过,这里就写None,否则报错 left_index,right_index:用左/右边的DataFrame某一列当做连接键Key sort:排序列 suffixes:如果两者有重复列名,重复项怎么命名,比如第一个有列名是ID,第二个也有列名是ID,那么第二个重复的列名将命名为ID_x copy:默认复制 ''' df_res = df1.merge(df2, how='left', on=['用户id','用户名'], left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True) # 排序 df_res.sort_values(by=['在看电影数','想看电影数']) #df_res.to_excel('res.xlsx',index=None)

 

最新回复(0)