我正在编写一个函数来使用数据框中每行的信息来选择另一个数据帧中的一些观察结果并返回一个数据框或列表:
df = pd.DataFrame({"D": [10,20,30], "p": [20, 30, 10]})
df1 = pd.DataFrame({"W": [20,30,30], "G": [10, 40, 10]})
def Compute(row):
df1.State = df1.apply(lambda r: 1 if r.W > row['D'] else 0, axis = 1)
df2 = df1[ (df1.State == 1) ]
if len(df2) > 0:
return df2
df.apply(Compute, axis = 1)
但是,我总是收到这样的错误:
Traceback (most recent call last):
File "<ipython-input-96-c5fdc35977db>", line 1, in <module>
df.apply(Compute, axis = 1)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\frame.py", line 3972, in apply
return self._apply_standard(f, axis, reduce=reduce)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4081, in _apply_standard
result = self._constructor(data=results, index=index)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\frame.py", line 226, in __init__
mgr = self._init_dict(data, index, columns, dtype=dtype)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\frame.py", line 363, in _init_dict
dtype=dtype)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\frame.py", line 5163, in _arrays_to_mgr
arrays = _homogenize(arrays, index, dtype)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\frame.py", line 5477, in _homogenize
raise_cast_failure=False)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\series.py", line 2887, in _sanitize_array
subarr = _asarray_tuplesafe(data, dtype=dtype)
File "C:\Users\Research\Anaconda3\lib\site-packages\pandas\core\common.py", line 2011, in _asarray_tuplesafe
result[:] = [tuple(x) for x in values]
ValueError: cannot copy sequence with size 2 to array axis with dimension 3
有没有办法完成这项工作?