如何将熊猫数据帧中的单元格值传递给移位函数?
下面是一些示例输入:
import pandas as pd
import numpy as np
df = pd.DataFrame(data={'x': [0,0,0,0,0,0,0,5,0,0],
'y': [np.nan,np.nan,np.nan,10,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})
df['z'] = np.where(df['x'].shift(1) > 0, (50 - df['y'].shift(5)), np.nan)
print(df)
df['a'] = np.where(df['x'].shift(1) > 0, (50 - df['y'].shift(df['x'].shift(1).get_value())), np.nan)
这是输出:
x y z
0 0 NaN NaN
1 0 NaN NaN
2 0 NaN NaN
3 0 10.0 NaN
4 0 NaN NaN
5 0 NaN NaN
6 0 NaN NaN
7 5 NaN NaN
8 0 NaN 40.0
9 0 NaN NaN
Traceback (most recent call last):
File "C:stockssandp500stack overflow question 1.py", line 11, in <module>
df['a'] = np.where(df['x'].shift(1) > 0, (50 - df['y'].shift(df['x'].shift(1).get_value())), np.nan)
TypeError: get_value() missing 1 required positional argument: 'label'
列"x"的值为 0 或介于 1 到 N 之间的某个整数。 这些整数是我想传递给 shift 函数以创建列"z"的值。 在"z"列中,我通过将"5"硬编码到移位函数中来作弊。 列"A"是我尝试将动态值从"X"列传递到 shift 函数。
在过去的 48 小时内,我已经尝试了数十种变体,但无法正常工作。 有人有想法吗? 提前谢谢。
我认为您尝试做的事情可以通过df.apply
来实现:
df = pd.DataFrame(data={'x': [0,0,0,0,0,0,0,5,0,0],
'y': [np.nan,np.nan,np.nan,10,np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})
我认为在独立函数中遵循逻辑比在 lambda 中更容易:
def shifter(mydf):
offset = int(mydf['offset'])
if offset>0:
val = 50 - df.shift(int(offset))['y'].loc[int(mydf['index'])]
else:
val = np.nan
return val
我用索引作为列制作了数据帧的副本,然后因为你在"x"列上做了额外的.shift(1)
,所以我做了一个名为offset
的辅助列,它只是提前这样做:
df2 = df.reset_index()
df2['offset'] = df2['x'].shift(1).fillna(0)
print(df2)
index x y offset
0 0 0 NaN 0.0
1 1 0 NaN 0.0
2 2 0 NaN 0.0
3 3 0 10.0 0.0
4 4 0 NaN 0.0
5 5 0 NaN 0.0
6 6 0 NaN 0.0
7 7 5 NaN 0.0
8 8 0 NaN 5.0
9 9 0 NaN 0.0
然后,您可以逐行应用移位器功能。请注意,它仍然引用该函数中的原始df
数据帧。它使用"索引"列中的值通过原始数据帧上的.loc
查找调整后的行。
df['z'] = df2.apply(shifter, axis=1)
print(df)
x y z
0 0 NaN NaN
1 0 NaN NaN
2 0 NaN NaN
3 0 10.0 NaN
4 0 NaN NaN
5 0 NaN NaN
6 0 NaN NaN
7 5 NaN NaN
8 0 NaN 40.0
9 0 NaN NaN
相关,作为参考,如果您只是想在没有额外逻辑的情况下获取偏移值:
df = pd.DataFrame(data={'x': [0,1,3,5,2,1,0,5,0,1],
'y': [2.0,4,3,10,1,77,28,56,42,48]})
def simple_shifter(mydf):
offset = int(mydf['x'])
val = df.shift(int(offset))['y'].loc[int(mydf['index'])]
return val
df3 = df.reset_index()
df['y_offset_by_x'] = df3.apply(simple_shifter, axis=1)
print(df)
x y y_offset_by_x
0 0 2.0 2.0
1 1 4.0 2.0
2 3 3.0 NaN
3 5 10.0 NaN
4 2 1.0 3.0
5 1 77.0 1.0
6 0 28.0 28.0
7 5 56.0 3.0
8 0 42.0 42.0
9 1 48.0 42.0
当然,如果数据帧很大,则需要进行速度优化,但这应该有效。