python - 有没有办法根据与 Pandas 中另一列关联的值来填充列?

标签 python excel pandas

我目前正在尝试使用一个非常大的数据集,但我需要先填充空白,然后才能有效地执行此操作。我正在使用的模型示例类似于 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

最佳答案

您可以将groupbyffill().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/

相关文章:

jquery - 使用 jQuery 使用 AJAX 发送 Excel 数据

python - 在 pandas DataFrame 中有效地将字符串转换为适当的数字类型

python - Unicode解码错误: 'ascii' codec can't decode byte 0x96 in position 10: ordinal not in range(128)

c# - C#获取最后一个数据填充的excel行号

sql - Excel 2010 32 位 Windows 7 64 位 odbc-连接问题

python - 为什么 "X for X in DataFrame"只给出列名

python - 属性错误 : 'Series' object has no attribute 'rolling'

python - NumPy:从每行中找到最大值,将其设置为 1,其余为 0

Python-我应该为指数型数据使用什么颜色图方案?

c++ - C/C++ 与 Python 之间交换值的应用程序设计