我目前正在尝试使用一个非常大的数据集,但我需要先填充空白,然后才能有效地执行此操作。我正在使用的模型示例类似于 Ex 1。“名称”仅在每个“团队”的“项目”列中填充 1 个值。
是否可以将“名称”列中的值分配给与其关联的相应“团队”编号的所有行,以类似于 Ex 2?我会在 Excel 文件中阅读。
我是 pandas 的新手,我不确定要专门查找什么才能找到这个答案,所以如果之前有人问过这个问题,我深表歉意。
Ex1
Team Item Name
1 Credit
1 Debit Bob
1 Etc
2 Credit
2 Debit Steve
2 Etc
Ex2
Team Item Name
1 Credit Bob
1 Debit Bob
1 Etc Bob
2 Credit Steve
2 Debit Steve
2 Etc Steve
最佳答案
您可以将groupby
与ffill().bfill()
链一起使用。
df['Name']=df.groupby('Team').Name.apply(lambda x : x.ffill().bfill())
df
Out[262]:
Team Item Name
0 1 Credit Bob
1 1 Debit Bob
2 1 Etc Bob
3 2 Credit Steve
4 2 Debit Steve
5 2 Etc Steve
关于python - 有没有办法根据与 Pandas 中另一列关联的值来填充列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54715483/