[英]Replace pandas column values with array
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. 我尝试使用replace,但是没有用。 Is there another way of doing this without turning array into a dataframe and merging?
还有另一种方法可以将数组转换为数据框并合并吗?
vals = [137.55021238, 125.30017675, 130.20181675, 109.47348838]
Option 1 选项1
Direct assignment. 直接分配。
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 选项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 选项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
(字符串)而不是NaN
(浮点数),则可以使用df.replace
进行转换:
df = df.replace('Nan', np.nan)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.