熊猫:从旧创建新列,添加值

ShanZhengYang

我有以下熊猫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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章