【问题标题】:adding a column to data frame based on function根据函数向数据框添加列
【发布时间】:2021-08-06 11:25:35
【问题描述】:
我有一个数据框,我编写了一个函数,对 df 中的每一行进行一些计算,
我想向 df 添加一列,该列具有我使用该函数进行的计算:
例如来自:
| Name |
first score |
second score |
third score |
| Dan |
4 |
3 |
2 |
| David |
3 |
6 |
3 |
| Jennifer |
4 |
5 |
6 |
到:
(将“最终分数”列添加到df,“最终分数”中的值将呈现使用我为每一行编写的函数的计算)
| Name |
first score |
second score |
third score |
Final score |
| Dan |
4 |
3 |
2 |
X |
| David |
3 |
6 |
3 |
Y |
| Jennifer |
4 |
5 |
6 |
Z |
非常感谢!
【问题讨论】:
标签:
python
dataframe
function
【解决方案1】:
.apply() 是您想要使用的。
df['Final Score'] = df.apply(function, axis=1)
将轴设置为 1 告诉它将函数应用于每一行
【解决方案2】:
df["final score"] = [function('first'), function('second'), function('third')]
【解决方案3】:
如果你有这样的事情:
dataframe = [['Dan', 4, 3, 2],
['David', 3, 6, 3],
['Jennifer', 4, 5, 6]]
那么你可以这样做:
for person in dataframe:
person += [0]
【解决方案4】:
你可以这样试试:
df['Final score'] = df.apply(lambda x: my_function(x['first score'], x['second score', x['third score']), axis=1)