python - Pandas:如果不同的给定列重复,如何组合列 int 值?

标签 python pandas

Stack Overflow 上有类似的问题,但没有一个适合我的情况。我尝试过使用 add(...)merge(...)concat(...) 的组合、 drop_duplicates(...) 等等,但我似乎无法弄清楚。

我之前正在处理数据,现在需要在 ID 匹配的情况下合并 A1、A2、B1、B2、B3、B4、B5 和 B6 列(均为 int 类型) (输入str)。新的“继承”什么FavoriteFood 或Index 并不重要。

给定数据:

Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   0    0    5    5    5    5    5    5
1      Hamburger     0012   0    0    12   12   12   12   12   12
2      Hamburger     0101   70   70   0    0    0    0    0    0
3      Hotdog        0012   21   21   0    0    0    0    0    0
4      Chili         0054   9    9    2    2    2    2    2    2
5      Cookie        2330   0    0    6    6    6    6    6    6
6      Pizza         0020   2    2    0    0    0    0    0    0

根据 ID 00540012,我们有以下匹配项:

Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   0    0    5    5    5    5    5    5
1      Hamburger     0012   0    0    12   12   12   12   12   12
3      Hotdog        0012   21   21   0    0    0    0    0    0
4      Chili         0054   9    9    2    2    2    2    2    2

因为 IndexFavouriteFood 和 DataFrame 的顺序并不重要,所以预期的 DataFrame 是:

Index  FavoriteFood  ID     A1   A2   B1   B2   B3   B4   B5   B6
0      Pizza         0054   9    9    7    7    7    7    7    7
2      Hamburger     0101   70   70   0    0    0    0    0    0
3      Hotdog        0012   21   21   12   12   12   12   12   12
5      Cookie        2330   0    0    6    6    6    6    6    6  
6      Pizza         0020   2    2    0    0    0    0    0    0    

如何像这样组合这些列?

最佳答案

您可以尝试使用字典agg:

agg_dict = {col: 'first' if col in ['FavoriteFood','Index'] else 'sum' 
            for col in df.columns if col!='ID'}
df.groupby('ID', as_index=False, sort=False).agg(agg_dict)

输出:

     ID  Index FavoriteFood  A1  A2  B1  B2  B3  B4  B5  B6
0  0054      0        Pizza   9   9   7   7   7   7   7   7
1  0012      1    Hamburger  21  21  12  12  12  12  12  12
2  0101      2    Hamburger  70  70   0   0   0   0   0   0
3  2330      5       Cookie   0   0   6   6   6   6   6   6
4  0020      6        Pizza   2   2   0   0   0   0   0   0

关于python - Pandas:如果不同的给定列重复,如何组合列 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60232710/

相关文章:

Python Pandas .DataFrame : Make whole row NaN according to condition

python - 为什么这个内存功能不能在线性时间内运行?

python - 如何将2个pandas数据框中的2列彼此相乘

pandas - 如何在 pandas 中使用数据透视表处理大块数据

pandas - future 警告 : Passing datetime64-dtype data to TimedeltaIndex is deprecated

python - Pandas 使用日期作为索引加入/合并 2 个数据帧

Python - 排序列表

python - 如何更新 Python?

python - django FileSystemStorage 的动态路径

python - 属性错误: 'list' object has no attribute 'lower' in TF-IDF