Skip to main content
 首页 » 编程设计

python之在 Pandas 中合并两行(一个有值,另一个为 NaN)

2025年02月15日7myhome

我知道之前有人问过类似的问题( How to merge two rows in a dataframe pandas 等),但我仍在努力执行以下操作(除了有很多行的 pandas 数据框):

    team_token  day1    day2   day3  day4 
0   abc          1      NaN     NaN   NaN 
1   abc          NaN     1      NaN   NaN 
2   abc          NaN     NaN    NaN    NaN 
3   abc          NaN     NaN    NaN     1 

我想合并具有相同 team_token 的行,以便最终结果如下所示:

    team_token  day1    day2  day3  day4 
0   abc           1      1    NaN     1 

提前谢谢你。

请您参考如下方法:

使用combine_first在数据框的两行给出的两个 Series 上:

import pandas as pd 
df = pd.DataFrame({'team_token':['abc', 'abc'], 'day1': [1, None], 'day2' : [None, 1]}) 
 
df.loc[0].combine_first(df.loc[1]) 

给出:

 team_token  day1    day2 
0   abc           1       1  

#编辑: 一个更好的解决方案也适用于您更新的答案很简单:

df.max() 

假设您的 day 列包含 Nan 或 ones。

如果您有不同的team_tokens:

   day1  day2  day3 team_token 
0   1.0   NaN   NaN        abc 
1   NaN   NaN   NaN        abc 
2   1.0   1.0   NaN        abc 
3   NaN   NaN   NaN        abc 
4   1.0   NaN   1.0        ddd 
5   1.0   NaN   1.0        ddd 
6   NaN   NaN   1.0        ddd 

您可以group_by 并仍然采用该组的max:

df.groupby('team_token').max().reset_index() 
 
#  team_token  day1  day2  day3 
#0        abc   1.0   1.0   NaN 
#1        ddd   1.0   NaN   1.0