如何根据多个列的条件汇总熊猫中的行,并删除重复项?

时间:2020-10-28 23:34:04

标签: python python-3.x pandas dataframe conditional-statements

首先,让我为冗长的问题表示歉意。我一直在努力找到关于Stackoverflow的答案,以解决我的特定问题。 我是Pandas和Python编程的新手,所以我将不胜感激。

我有一个数据框:

 ID            Name  Colour      Power  Year  Money (millions)
0   1234567      Tony Stark     Red     Genius  2020             20000
1   9876543    Peter Parker     Red     Spider  2021                75
2   1415926   Miles Morales   Green     Spider  2021                55
3   7777777    Dante Brisco    Blue     hybrid  2020                 3
4   4355681    Thor Odinson    Blue  Lightning  2020               655
5   1928374     Bruce Wayne  Yellow        Bat  2021             12000
6   5555555     Eddie Brock   Black   Symbiote  2021               755
7   8183822  Billie Butcher  Yellow          V  2021                34
8   6666654        Ian Wilm     Red  Lightning  2020                34
9   4241111    Harry Potter   Green     Wizard  2020                24
10  7765434        Blu Malk     Red     Wizard  2021                77
11  6464647         Yu Hant   Black     Wizard  2021                65

我想创建一个新的df,如下所示:

 **Colour    Total      Year 2020     Year 2021**
 Red        20186     20034          152
 Green      79        24             55 
 Blue       658       658            -------
 Yellow     12034     -------        12034
 Black      820       -------        820

“颜色”列成为新的主键/ ID时,将删除重复项,并将每年的值与总数进行汇总。我设法总结了总数,但我在努力编写一个函数,该函数将按年对行进行求和,然后将总和分配给相应的颜色。我最终希望根据“年度”列(百分比)的计算来创建新列

这是从excel文件创建DF之后的内容:

#This line helps me calculate the total from the old df. 
df['Total'] = df.groupby(['Colour'])['Money (millions)'].transform('sum') 

#This line drops the duplicates from the line above. So now I have a total column that matches the #Colours
new_df = df.drop_duplicates(subset=['Colour'])

当我使用相同的技术对Yearly(年度)列重复该过程时,它将汇总全年的总计并将其分配给每种颜色。

我最终想根据“年”列(百分比)中的计算结果创建新列。

 new_df['Success Rate'] = new_df['Total'].apply(lambda x: (x/100)*33)

感谢提供的帮助:)

2 个答案:

答案 0 :(得分:2)

您可以使用:

df = pd.pivot_table(df, index='Colour', values='Money (millions)', columns='Year', aggfunc='sum', margins=True)
df
Out[1]: 
Year       2020     2021    All
Colour                         
Black       NaN    820.0    820
Blue      658.0      NaN    658
Green      24.0     55.0     79
Red     20034.0    152.0  20186
Yellow      NaN  12034.0  12034
All     20716.0  13061.0  33777

答案 1 :(得分:2)

我认为这是pivot_tablemargins

df.pivot_table(index='Colour', columns='Year', 
               values='Money (millions)',
               aggfunc='sum',
               margins_name='Total',
               margins=True)

输出:

Year       2020     2021  Total
Colour                         
Black       NaN    820.0    820
Blue      658.0      NaN    658
Green      24.0     55.0     79
Red     20034.0    152.0  20186
Yellow      NaN  12034.0  12034
Total   20716.0  13061.0  33777