【发布时间】:2019-04-01 16:54:51
【问题描述】:
我有一个这样的熊猫数据框:
df1:
id name gender
1 Alice Male
2 Jenny Female
3 Bob Male
现在我想添加一个新的列运动,它将包含列表形式的值。让我想将足球添加到性别为男性的行中,所以 df1 看起来像:
df1:
id name gender sport
1 Alice Male [Football]
2 Jenny Female NA
3 Bob Male [Football]
现在,如果我想将 Badminton 添加到性别为女性的行,将网球添加到性别为男性的行,最终输出为:
df1:
id name gender sport
1 Alice Male [Football,Tennis]
2 Jenny Female [Badminton]
3 Bob Male [Football,Tennis]
如何在python中编写一个通用函数来完成根据其他列值将新值附加到列中的任务?
【问题讨论】:
-
没有这样的通用函数。 或者,如果你选择炮制一个,它会与 Pandas 使用容器作为序列值背道而驰。可能,自定义类或
dict+list是更合适的数据结构选择。
标签: python-3.x pandas