我正在尝试将系列的值添加到数据框中。我不是试图将列添加到数据帧的末尾,即在数据框中创建一个额外的列。
我的序列长度与数据帧的列数相同。我想将系列中的值添加到框架中的每一列。
我试过了Dataframe.add()
但它没有用。
代码: Dataframe(命名读者):
Current track blade 1 Current track blade 2
0 -8.577881 -0.333252
1 -6.284912 5.294434
2 6.269775 11.229490
3 5.253418 10.187260
4 -16.088380 -2.967773
要添加到每列的系列(名为abs_track):
Current abs track
0 3503.125
1 3517.333
2 3504.778
3 3476.127
4 3477.776
reader=reader+abs_track
和reader.add('abs_track')
给出:
Current abs track Current track blade 1 Current track blade 2
0 NaN NaN NaN
1 NaN NaN NaN
2 NaN NaN NaN
3 NaN NaN NaN
4 NaN NaN NaN
任何想法。
答案 0 :(得分:5)
您需要传递参数axis=0
才能达到您想要的效果:
df = pd.DataFrame({"Current track blade 1":[-8.577881, -6.284912, 6.269775, 5.253418, -16.088380], "Current track blade 2": [-0.333252, 5.294434, 11.229490,10.187260,-2.967773]})
s = pd.Series([3503.125, 3517.333, 3504.778, 3476.127, 3477.776])
df.add(s, axis=0)
Out[58]:
Current track blade 1 Current track blade 2
0 3494.547119 3502.791748
1 3511.048088 3522.627434
2 3511.047775 3516.007490
3 3481.380418 3486.314260
4 3461.687620 3474.808227
这将按列添加而不是按行添加,这是默认值。
答案 1 :(得分:2)
你可以使用apply函数:
>>> df1 = pd.DataFrame({"Current track blade 1":[-8.577881, -6.284912, 6.269775, 5.253418, -16.088380], "Current track blade 2": [-0.333252, 5.294434, 11.229490,10.187260,-2.967773]})
>>> s1 = pd.Series([3503.125, 3517.333, 3504.778, 3476.127, 3477.776])
>>> df1.apply(lambda x: x + s1)
Current track blade 1 Current track blade 2
0 3494.547119 3502.791748
1 3511.048088 3522.627434
2 3511.047775 3516.007490
3 3481.380418 3486.314260
4 3461.687620 3474.808227