gpt4 book ai didi

python - Pandas:从旧列创建新列,添加值

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:40 26 4
gpt4 key购买 nike

我有以下 pandas DataFrame:

import pandas as pd
import numpy as np
data = 'filename.csv'
df = pd.DataFrame(data)
df

one two three four five
a 0.469112 -0.282863 -1.509059 bar True
b NaN 1.224234 7.823421 bar False
c -1.135632 1.212112 -0.173215 bar False
d NaN NaN NaN NaN True
e 0.119209 -1.044236 -0.861849 bar True
f -2.104569 -0.494929 1.071804 bar False

我只想创建一个新列“oneplus20”,以便将浮点 20.0 添加到“one”列中的每个单元格。所以,我尝试

df['oneplus20'] = df.apply(lambda row: row['one'] + 20, axis=1)

这行不通。我很困惑为什么没有。

做这样的事情的正确方法是什么?

最佳答案

试试这个:

df['oneplus20'] = df['one'] + 20.0

演示:

In [36]: df['oneplus20'] = df['one'] + 20.0

In [37]: df
Out[37]:
one two three four five oneplus20
a 0.469112 -0.282863 -1.509059 bar True 20.469112
b NaN 1.224234 7.823421 bar False NaN
c -1.135632 1.212112 -0.173215 bar False 18.864368
d NaN NaN NaN NaN True NaN
e 0.119209 -1.044236 -0.861849 bar True 20.119209
f -2.104569 -0.494929 1.071804 bar False 17.895431

或者如果您想用零替换 NaN:

In [45]: df['oneplus20'] = df['one'].fillna(0) + 20.0

In [46]: df
Out[46]:
one two three four five oneplus20
a 0.469112 -0.282863 -1.509059 bar True 20.469112
b NaN 1.224234 7.823421 bar False 20.000000
c -1.135632 1.212112 -0.173215 bar False 18.864368
d NaN NaN NaN NaN True 20.000000
e 0.119209 -1.044236 -0.861849 bar True 20.119209
f -2.104569 -0.494929 1.071804 bar False 17.895431

关于python - Pandas:从旧列创建新列,添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38001588/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com