Python 实现`df[m]=df[x]&x2B;df[y]和#x2B;df[z]`
我想得到三列的和,我采用的方法如下:Python 实现`df[m]=df[x]&x2B;df[y]和#x2B;df[z]`,python,pandas,apply,nan,Python,Pandas,Apply,Nan,我想得到三列的和,我采用的方法如下: In [14]: a_pd = pd.DataFrame({'a': np.arange(3), 'b': [5, 7, np.NAN], 'c': [2, 9, 0]}) a_pd Out[14]: a b c 0 0 5.0 2 1 1 7.0 9 2 2 NaN 0 In [18]: b_pd = a_pd['a'] + a_pd['
In [14]:
a_pd = pd.DataFrame({'a': np.arange(3),
'b': [5, 7, np.NAN],
'c': [2, 9, 0]})
a_pd
Out[14]:
a b c
0 0 5.0 2
1 1 7.0 9
2 2 NaN 0
In [18]:
b_pd = a_pd['a'] + a_pd['b'] + a_pd['c']
b_pd
Out[18]:
0 7.0
1 17.0
2 NaN
dtype: float64
但正如你所看到的,楠不能被排除在外。
因此我尝试了np.add()
,但出现了一些问题:
In [19]:
b_pd = a_pd[['a', 'b', 'c']].apply(np.add, axis=1)
b_pd
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-19-f52f400573b4> in <module>()
----> 1 b_pd = a_pd[['a', 'b', 'c']].apply(np.add, axis=1)
2 b_pd
F:\anaconda\lib\site-packages\pandas\core\frame.pyc in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
4045
4046 if isinstance(f, np.ufunc):
-> 4047 results = f(self.values)
4048 return self._constructor(data=results, index=self.index,
4049 columns=self.columns, copy=False)
ValueError: invalid number of arguments
[19]中的
b_pd=a_pd[[a',b',c']]。应用(np.add,axis=1)
b_pd
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在()
---->1 b_pd=a_pd[[a',b',c']]。应用(np.add,axis=1)
2 b_pd
应用中的F:\anaconda\lib\site packages\pandas\core\frame.pyc(self、func、axis、broadcast、raw、reduce、args、**kwds)
4045
4046如果存在(f,np.ufunc):
->4047结果=f(自身值)
4048返回self.\u构造函数(数据=结果,索引=self.index,
4049列=self.columns,copy=False)
ValueError:参数数无效
因此,我想知道如何修复此错误。您可以使用数据帧的求和方法:
a_pd.sum(axis=1)
Out:
0 7.0
1 17.0
2 2.0
dtype: float64
如果要指定列,请执行以下操作:
a_pd[['a', 'b', 'c']].sum(axis=1)
Out:
0 7.0
1 17.0
2 2.0
dtype: float64
np.add需要输入
b_pd = a_pd[['a', 'b', 'c']].apply(np.sum, axis=1)
很好~我不明白为什么轴=1。我认为轴=0是正确的,因为加号在水平方向。@QM.py实际上相反。如果要按列执行操作,请使用
axis=0
(默认情况下通常为0),但如果要按行应用,请使用axis=1
。查看更详细的答案。np.add
需要两个输入。这可以是两个标量或两个数组(np.add(例如a_-pd['a'],a_-pd['b'])
)。但是apply
在pd.Series类型的单独列或行上应用该函数。因此,由于您只传递一个数组,它表示参数的数量是错误的。