这是我的代码:
a = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=['A', 'B'])
print(a)
a['C'] = 1 # or np.nan or is there a way to avoid this?
b = lambda i : i['A'] + i['B'] + i['C'] # actually what is needed if to access a previous element, like i['C'].shift()
a['C'] = a.apply(b, axis=1)
print(a)
哪个工作正常,但在lambda中,我想访问i['C'].shift(1)
但如果以这种方式使用它我会得到以下异常;
Traceback (most recent call last):
File "C:\Users\Development\workspace\TestPython\TestPython.py", line 31, in <module>
a['C'] = a.apply(b, axis=1)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\frame.py", line 4262, in apply
ignore_failures=ignore_failures)
File "C:\Program Files\Python36\lib\site-packages\pandas\core\frame.py", line 4358, in _apply_standard
results[i] = func(v)
File "C:\Users\Development\workspace\TestPython\TestPython.py", line 29, in <lambda>
b = lambda i : i['A'] + i['B'] + i['C'].shift() # actually what is needed if to access a previous element, like i['C'].shift()
AttributeError: ("'numpy.int64' object has no attribute 'shift'", 'occurred at index 0')
我还想避免初始化a['C'] = 1
,如果可能的话,这意味着[&#39; C&#39;]是在此操作中添加的新列。
任何建议或替代方法实现此目标?
答案 0 :(得分:0)
我想你需要这个:
a['C'] = a['A'] + a['B']
a['D'] = a['C'].cumsum()
因为与前一元素的求和是一个累积和。
答案 1 :(得分:0)
从你的代码:
# Variable a BEFORE apply
A B
0 1 2
1 3 4
2 5 6
3 7 8
4 9 10
# Variable a AFTER apply
A B C
0 1 2 4
1 3 4 8
2 5 6 12
3 7 8 16
4 9 10 20
假设这个输出真的是你想要的,那么:
a = pd.DataFrame([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]], columns=['A', 'B'])
a['C'] = a['A'] + a['B'] + 1
我对你为什么要访问a['C'].shift(1)
感到有点困惑,因为无论如何所有的值都是相同的,你试图不对它进行初始化。
如果您想要使用df.shift(n)
的实际示例,请尝试:
a['Shift'] = a['A'] + a['B'].shift(1)
哪会给你:
A B C Shift
0 1 2 4 NaN
1 3 4 8 5.0
2 5 6 12 9.0
3 7 8 16 13.0
4 9 10 20 17.0
这会给你A(i)+ B(i + 1),其中i是行号。由于您将B列移动了1,因此第一个总和为NaN
。