Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在自身摘要上加入dataframe后,dataframe中出现奇怪的列名_Python_Pandas - Fatal编程技术网

Python 在自身摘要上加入dataframe后,dataframe中出现奇怪的列名

Python 在自身摘要上加入dataframe后,dataframe中出现奇怪的列名,python,pandas,Python,Pandas,当我总结一个数据帧并将其连接回原始数据帧时,我在处理列名时遇到了问题 这是原始数据帧: import pandas as pd d = {'col1': ["a", "a", "b", "a", "b", "a"], 'col2': [0, 4, 3, -5, 3, 4]} df = pd.DataFrame(data=d) 现在,我计算一些统计数据并将摘要合并回: group_summary = df.groupby('col1', as_index = False).agg({'col2

当我总结一个数据帧并将其连接回原始数据帧时,我在处理列名时遇到了问题

这是原始数据帧:

import pandas as pd

d = {'col1': ["a", "a", "b", "a", "b", "a"], 'col2': [0, 4, 3, -5, 3, 4]}
df = pd.DataFrame(data=d)
现在,我计算一些统计数据并将摘要合并回:

group_summary = df.groupby('col1', as_index = False).agg({'col2': ['mean', 'count']})
df = pd.merge(df, group_summary, on = 'col1')
dataframe现在有一些奇怪的列名:

df
Out: 
  col1  col2  (col2, mean)  (col2, count)
0    a     0          0.75              4
1    a     4          0.75              4
2    a    -5          0.75              4
3    a     4          0.75              4
4    b     3          3.00              2
5    b     3          3.00              2
我知道我可以使用像
df.iloc[:,2]
这样的列,但我也希望像
df['(col2,mean)]
那样使用它们,但这会返回一个
keyrerror


来源:这源于前面的问题。

这是因为您的
GroupBy.agg
操作会产生一个多索引数据帧,并且当将一个单级标题数据帧与一个多索引数据帧合并时,多索引会转换为平面元组

按如下方式修复groupby代码:

group_summary = df.groupby('col1', as_index=False)['col2'].agg(['mean', 'count'])
“合并”现在提供扁平列

df.merge(group_summary, on='col1')

  col1  col2  mean  count
0    a     0  0.75      4
1    a     4  0.75      4
2    a    -5  0.75      4
3    a     4  0.75      4
4    b     3  3.00      2
5    b     3  3.00      2

更好的方法是使用
transform
将输出映射到输入维度

g = df.groupby('col1', as_index=False)['col2']
df.assign(mean=g.transform('mean'), count=g.transform('count'))

  col1  col2  mean  count
0    a     0  0.75      4
1    a     4  0.75      4
2    b     3  3.00      2
3    a    -5  0.75      4
4    b     3  3.00      2
5    a     4  0.75      4

专业提示,您可以使用
descripe
在单个函数调用中计算一些有用的统计信息

df.groupby('col1').describe()

      col2                                          
     count  mean       std  min   25%  50%  75%  max
col1                                                
a      4.0  0.75  4.272002 -5.0 -1.25  2.0  4.0  4.0
b      2.0  3.00  0.000000  3.0  3.00  3.0  3.0  3.0
也看到