python - 从pandas中的多级groupby中进行选择

标签 python pandas

假设我有两个数据框:带有列 ('a', 'b', 'c') 的 df 和带有 ('a', 'b')< 列的 tf。我对 df 中的两个公共(public)列进行分组合并:

grouped_sum = df.groupby(('a', 'b')).sum()

如何根据grouped_sum将列c“添加”到tf,即

tf[i]['c'] = grouped_sum[tf[i]['a'], tf[i]['b']]

对于第二个数据帧的所有行i?对于具有单个级别的 groupby,它只需使用 tf 的相应列对组进行索引即可工作。

最佳答案

如果您使用 as_index=False 进行分组,则可以与 tf 合并:

In [11]: tf = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))

In [12]: df = pd.DataFrame([[1, 2, 3], [1, 2, 4], [3, 4, 5]], columns=list('abc'))

In [13]: grouped_sum = df.groupby(['a', 'b'], as_index=False).sum()

In [14]: grouped_sum
Out[14]:
   a  b  c
0  1  2  7
1  3  4  5

In [15]: tf.merge(grouped_sum)  # this won't always be the same as grouped_sum!
Out[15]:
   a  b  c
0  1  2  7
1  3  4  5

另一种选择是将a和b设置为tf的索引

关于python - 从pandas中的多级groupby中进行选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25575175/

相关文章:

python - 使用 OpenCV 和 SIFT/SURF 校正扫描图像以匹配原始图像

python - 将线图重叠到 pandas 中的水平条形图

python - protobuf python 错误 "cannot assign to extension because it is a repeated or composite type"

python-3.x - 在 Pandas Dataframe 列中查找某些单词,如果找到,将它们添加到新列中

python - Python中列表列表上的滑动窗口

python - numpy.histogram2d 在传递子集 pandas.DataFrame 时引发异常

python - 在for循环中更改django表单的ID

python - 如何提高jdbc的spark.write性能?

python - 取消聚合 Pandas 中的字符串值字段

python - 无法加入字符串类型的 Pandas 数据框