pandas官方文档:https://pandas.pydata.org/docs/reference/
DataFrame官方文档:https://pandas.pydata.org/docs/reference/frame.html
添加新列:https://www.geeksforgeeks.org/adding-new-column-to-existing-dataframe-in-pandas/
创建
构造函数:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html
从已有列创建
a = [1, 2, 3] |
a b |
从Series list创建
li = [] |
a b c |
从stdin读取
直接把sys.stdin
当file输入进去即可:
latencies = pd.read_table(sys.stdin, names=['operation', 'latency(ns)'], sep=r'\s+') |
来源:https://stackoverflow.com/questions/18495846/pandas-data-from-stdin
添加新行
https://pandas.pydata.org/docs/reference/api/pandas.concat.html#pandas.concat
注意,append已经被deprecated了:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html
如果需要把Series作为行添加到DataFrame里,需要先将其转换成DataFrame,再转置:
r = pd.Series([1, 2, 3], index = ['col1', 'col2', 'col3']) |
注意,pd.concat
会返回一个新的DataFrame,所以复杂度是O(n)
的:https://stackoverflow.com/a/36489724/13688160
根据index取出行
用.iloc
,与python自带的list的语法类似:
test = pd.DataFrame({'col1': range(0, 10), 'col2': range(10, 20)}) |
取出满足条件的行
# 选择年龄大于25岁且性别为男性的数据行 |
来源:https://www.ycpai.cn/python/UcXZsYr8.html
取出多列
test = pd.DataFrame({'col1': [0, 1], 'col2': [2, 3], 'col3': [4, 5]}) |
输出:
col2 col1 |
取出并删除某列
test = pd.DataFrame({'col1': [0, 1], 'col2': [2, 3], 'col3': [4, 5]}) |
0 0 |
求均值
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.mean.html
test = pd.DataFrame({'col1': [0, 1, 2, 3], 'col2': [4, 5, 6, 7]}) |
groupby
https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.groupby.html
每3行分组并求均值
test = pd.DataFrame({'col1': range(0, 10), 'col2': range(10, 20)}) |
输出:
col1 col2 |
将某列的值相同的合并成一个list
https://stackoverflow.com/questions/22219004/how-to-group-dataframe-rows-into-list-in-pandas-groupby
遍历
https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas
前缀和
test = pd.DataFrame({'col1': [0, 1, 2, 3], 'col2': [4, 5, 6, 7]}) |
转dict
https://stackoverflow.com/questions/18695605/how-to-convert-a-dataframe-to-a-dictionary
df.set_index('id') |
然后就变成了一个dict-like了,value是其他所有列。
如果要得到映射到另一列的dict:
df.set_index('id')['column'] |
转成真正的dict:
df.set_index('id')['column'].to_dict() |
按照某个有序field合并数据框
类似于数据库里的JOIN:
d1 = pd.DataFrame({'a': [1, 2], 'b': [1, 2]}) |
输出:
a b_x b_y |
同名的列会加上后缀。所以建议在merge前把其他列名改成全局唯一的:
d1 = d1.rename(columns={'b': 'b1'}) |
a b1 b2 |
如果要把NaN
转成0
:
pd.merge_ordered(d1, d2, on='a', how='outer').fillna(0) |