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

时间:2016-06-23 20:48:38

标签: python pandas

我有以下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添加到列'中的每个单元格中。所以,我试试

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

这不起作用。我很困惑为什么它没有。

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

1 个答案:

答案 0 :(得分: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
相关问题