Python用一列表示数据帧的和

2024-03-28 12:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

Python有一个Pandas数据帧:

df = pd.DataFrame(np.random.rand(5,3),columns=list('ABC'))
print df
              A           B           C
0   0.041761178 0.60439116  0.349372206
1   0.820455992 0.245314299 0.635568504
2   0.517482167 0.7257227   0.982969949
3   0.208934899 0.594973111 0.671030326
4   0.651299752 0.617672419 0.948121305

问题: 我想将第一列添加到整个数据帧。我想要这个:

^{pr2}$

第一行:

  • A: 0.04176+0.04176=0.08352
  • B: 0.04176+0.60439=0.64615
  • 等等

要求: 我不能使用第一列的列名来引用它。 例如:df.A不可接受;df.iloc[:,0]是可接受的。在

尝试: 我试过使用:

print df.add(df.iloc[:,0], fill_value=0)

但它不起作用。它返回错误消息:

Traceback (most recent call last):
  File "C:test.py", line 20, in <module>
    print df.add(df.iloc[:,0], fill_value=0)
  File "C:\python27\lib\site-packages\pandas\core\ops.py", line 771, in f
    return self._combine_series(other, na_op, fill_value, axis, level)
  File "C:\python27\lib\site-packages\pandas\core\frame.py", line 2939, in _combine_series
    return self._combine_match_columns(other, func, level=level, fill_value=fill_value)
  File "C:\python27\lib\site-packages\pandas\core\frame.py", line 2975, in _combine_match_columns
    fill_value)
NotImplementedError: fill_value 0 not supported

是否可以将数据帧的所有列与第一列相加?在


Tags: columns数据inpydfvaluelibline
3条回答

我会试试这样的方法:

firstol = df.columns[0]
df2 = df.add(df[firstcol], axis=0)

我综合以上两篇文章来回答这个问题。在

因为我不能通过名称来引用特定列,所以不能使用df.add(df.A, axis=0)。但这是正确的。由于df += df[firstcol]产生了一个NaNs的数据帧,所以我不能使用这种方法,但是这个解决方案从数据帧中获取列列表的方法是我需要的技巧。在

我是这样做的:

col_0 = df.columns.tolist()[0]
print(df.add(df[col_0], axis=0))

这就是你需要做的:

df.add(df.A, axis=0)


Example:
>>> df = pd.DataFrame(np.random.rand(5,3),columns=['A','B','C'])
>>> col_0 = df.columns.tolist()[0]

>>> print df
          A         B         C
0  0.502962  0.093555  0.854267
1  0.165805  0.263960  0.353374
2  0.386777  0.143079  0.063389
3  0.639575  0.269359  0.681811
4  0.874487  0.992425  0.660696
>>> df = df.add(df.col_0, axis=0)
>>> print df
          A         B         C
0  1.005925  0.596517  1.357229
1  0.331611  0.429766  0.519179
2  0.773553  0.529855  0.450165
3  1.279151  0.908934  1.321386
4  1.748975  1.866912  1.535183
>>> 

相关问题 更多 >