我知道以前曾问过类似的问题(如何在数据框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或一。
如果您有不同的话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
我会尝试!我意识到现在我的1实际上是字符串,因此将修复并尝试上述操作,这应该可以工作!谢谢!
凉!很高兴听您这么说