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


我使用如下命令

>>> df_new['total pts'].add(df_new['resistance 1 '],fill_value=0)


它返回错误

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来代替加法,但是我需要进行减法,除法和乘法。我想知道为什么这些运算符不起作用。

最佳答案

您可以尝试通过stringresistance 1float强制转换为astype

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'>


投放后,您将获得:

df_new['resistance 1 '] = df_new['resistance 1 '].astype(float)

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

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




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


如果不强制转换sum仅列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

关于python - Pandas :数据框的总和加法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36065627/

10-12 18:41