【问题标题】:Add pandas column values only when 1 column value is == to another column value仅当 1 列值 == 到另一列值时才添加 pandas 列值
【发布时间】:2021-03-17 15:45:10
【问题描述】:

我很头晕,如果有任何帮助,我将不胜感激。我有一个 python pd 数据框。目标是获得每年的总数。为此,我必须将“start”列的“freq”添加到“add_year”列的“freq2”中,前提是“start”与“added_year”匹配。

gender  start   freq    added_year  freq2
0   0   1789    89  1790    89
28  0   1790    6   1791    6
31  0   1791    82  1792    82
69  0   1792    4   1793    4
70  0   1793    123 1794    123

the output would be something along the lines of

start    freq      added_year   freq2     total
1790        6            1790      89        95'''

I think I have to do some kind of map/lambda function or a define a function with a series of if statements, but I am confused as to how to do this.
Thank you.

【问题讨论】:

    标签: python pandas dataframe lambda calculated-columns


    【解决方案1】:

    你可以做一个自我合并,然后取一个总和。

    df = df[['start','freq']].merge(df[['added_year','freq2']], left_on='start', right_on='added_year')
    
    df['total'] = df['freq']+df['freq2']
    

    输出

       start  freq  added_year  freq2  total
    0   1790     6        1790     89     95
    1   1791    82        1791      6     88
    2   1792     4        1792     82     86
    3   1793   123        1793      4    127
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 2019-01-04
      • 1970-01-01
      相关资源
      最近更新 更多