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

10-12 21:42