问题 1:
我有一个包含两个月值列的数据框,分别为 month1
和 month2
。如果 month1
列中的值不是 NA
,则根据 month1
列对相应的 amount
值求和。如果month1
列中的值为NA
,则选择'month2'对应的值并在month1
列中搜索并执行求和。
import pandas as pd
df = pd.DataFrame(
{
'month1': [1, 2, 'NA', 1, 4, 'NA', 'NA'],
'month2': ['NA', 5, 1, 2, 'NA', 1, 3],
'amount': [10, 20, 40, 50, 60, 70, 100]
}
)
问题 1 的预期输出:
month1 month2 sum_amount
0 1.0 NaN 60
1 2.0 5.0 20
2 NaN 1.0 60
3 1.0 2.0 60
4 4.0 NaN 60
5 NaN 1.0 60
6 NaN 3.0 0
问题 2:
我有一个包含两个月值列的数据框,分别为 month1
和 month2
。如果 month1
列中的值不是 NA
,则根据 month2
列对相应的 amount
值求和。如果month1
列中的值为NA
,则选择month2
对应的值并在month2
中搜索列并进行求和。
import pandas as pd
df = pd.DataFrame(
{
'month1': [1, 2, 'NA', 1, 4, 'NA', 'NA'],
'month2': ['NA', 5, 1, 2, 'NA', 1, 3],
'amount': [10, 20, 40, 50, 60, 70, 100]
}
)
问题 2 的期望输出:
month1 month2 sum_amount
0 1.0 NaN 110
1 2.0 5.0 50
2 NaN 1.0 110
3 1.0 2.0 110
4 4.0 NaN 0
5 NaN 1.0 110
6 NaN 3.0 100
最佳答案
我的解决方案不是很优雅,但很有效。看看。
您的两个问题的相同部分是:
In [1]: import pandas as pd
df = pd.DataFrame(
{
'month1': [1, 2, 'NA', 1, 4, 'NA', 'NA'],
'month2': ['NA', 5, 1, 2, 'NA', 1, 3],
'amount': [10, 20, 40, 50, 60, 70, 100],
}
)
def make_sum_amount(row, amount_sum):
if row['month1'] == 'NA':
if row['month2'] == 'NA':
return 0
return amount_sum.get(row['month2'], 0)
return amount_sum.get(row['month1'], 0)
第一个问题的解答:
In [2]: grouped_df = df[df['month1']!='NA'].groupby('month1').sum().reset_index()
amount_sum = {k: v for k, v in zip(grouped_df['month1'], grouped_df['amount'])}
df['sum_amount'] = df.apply(lambda row: make_sum_amount(row, amount_sum), axis=1)
df
Out [2]: month1 month2 amount sum_amount
0 1.0 NA 10 60
1 2.0 5.0 20 20
2 NA 1.0 40 60
3 1.0 2.0 50 60
4 4.0 NA 60 60
5 NA 1.0 70 60
6 NA 3.0 100 0
第二题解法:
In [3]: grouped_df = df[df['month2']!='NA'].groupby('month2').sum().reset_index()
amount_sum = {k: v for k, v in zip(grouped_df['month2'], grouped_df['amount'])}
df['sum_amount'] = df.apply(lambda row: make_sum_amount(row, amount_sum), axis=1)
df
Out [3]: month1 month2 amount sum_amount
0 1.0 NA 10 110
1 2.0 5.0 20 50
2 NA 1.0 40 110
3 1.0 2.0 50 110
4 4.0 NA 60 0
5 NA 1.0 70 110
6 NA 3.0 100 100
关于python - 应用多个条件级别的 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57520736/