Pandas:数据帧求和和和

2024-04-29 01:05:32 发布

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

         total pts resistance 1 
0          0.5         0.872
1          2.0         1.770
2          0.0         0.246
3          2.0         3.500
4          0.5         1.069
5          1.0         0.793
6          0.5           nan
7          1.5         1.394

我使用如下命令

^{pr2}$

它返回错误

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/ops.py", line 686, in flex_wrapper
    return self._binop(other, op, level=level, fill_value=fill_value)
  File "/usr/local/lib/python2.7/dist-packages/pandas/core/series.py", line 1459, in _binop
    result = func(this_vals, other_vals)
TypeError: unsupported operand type(s) for +: 'float' and 'str'

但它与下面的命令完美配合

>>> df_new[['total pts','resistance 1 ']].sum(axis=1)

问题是我可以用sum代替add,但我需要做减法、除法和乘法。我想知道这些接线员为什么不工作。在


Tags: inpycore命令pandaslibpackagesusr
1条回答
网友
1楼 · 发布于 2024-04-29 01:05:32

您可以尝试通过^{}stringresistance 1转换为{}:

print df_new
   total pts resistance 1
0        0.5        0.872
1        2.0         1.77
2        0.0        0.246
3        2.0          3.5
4        0.5        1.069
5        1.0        0.793
6        0.5          nan
7        1.5        1.394

print df_new.dtypes
total pts       float64
resistance 1     object
dtype: object

print type(df_new.loc[0, 'resistance 1 '])
<type 'str'>

施放后你会得到:

^{pr2}$
print df_new['total pts'].add(df_new['resistance 1 '].astype(float), fill_value=0)
0    1.372
1    3.770
2    0.246
3    5.500
4    1.569
5    1.793
6    0.500
7    2.894
dtype: float64

如果不强制转换^{}仅限列total pts,则忽略列resistance 1的值:

print df_new[['total pts','resistance 1 ']].sum(axis=1)
0    0.5
1    2.0
2    0.0
3    2.0
4    0.5
5    1.0
6    0.5
7    1.5
dtype: float64

相关问题 更多 >