pandas 用数组替换熊猫列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46760288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:38:38  来源:igfitidea点击:

Replace pandas column values with array

pythonpandas

提问by Adam Schroeder

I have an array:

我有一个数组:

([ 137.55021238,  125.30017675,  130.20181675,  109.47348838])

I need the array values to replace the b column, with the index number remaining the same:

我需要数组值来替换 b 列,索引号保持不变:

Index    a         b         
0       0.671399 Nan
35      0.446172 Nan
63      0.614758 Nan
72      0.634448 Nan

I tried to use replace but it didn't work. Is there another way of doing this without turning array into a dataframe and merging?

我尝试使用替换,但没有用。是否有另一种方法可以在不将数组转换为数据帧并合并的情况下执行此操作?

回答by cs95

vals = [137.55021238, 125.30017675, 130.20181675, 109.47348838]


Option 1
Direct assignment.

选项 1
直接分配。

df['b'] = vals
print(df)
              a           b
Index
0      0.671399  137.550212
35     0.446172  125.300177
63     0.614758  130.201817
72     0.634448  109.473488


Option 2
df.assign

选项 2
df.assign

df = df.assign(b=vals)
print(df)
              a           b
Index
0      0.671399  137.550212
35     0.446172  125.300177
63     0.614758  130.201817
72     0.634448  109.473488


Option 3
df.fillna

选项 3
df.fillna

df.b = df.b.fillna(pd.Series(vals, index=df.index))
print(df)
              a           b
Index
0      0.671399  137.550212
35     0.446172  125.300177
63     0.614758  130.201817
72     0.634448  109.473488

If your values are Nan(string) instead of NaN(float), you can convert it, using df.replace:

如果您的值是Nan(string) 而不是NaN(float),您可以使用df.replace以下命令对其进行转换:

df = df.replace('Nan', np.nan)