pandas 的变迁 [英] Variable shift in Pandas
本文介绍了 pandas 的变迁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在数据框中具有两列A和B:
having two columns A and B in a dataframe:
A B
0 1 6
1 2 7
2 1 8
3 2 9
4 1 10
我想创建一列C.C必须将B的值偏移A的值:
I would like to create a column C. C must have values of B shifted by value of A:
A B C
0 1 6 NaN
1 2 7 NaN
2 1 8 7
3 2 9 7
4 1 10 9
命令:
df['C'] = df['B'].shift(df['A'])
不起作用. 您还有其他想法吗?
does not work. Do you have any other ideas?
推荐答案
由于索引对齐,这很棘手,您可以在df上定义用户func和apply
按行,此处该函数将在B列并返回已移位列的索引值(使用.name
属性返回索引):
This is tricky due to index alignment, you can define a user func and apply
row-wise on your df, here the function will perform a shift on the B column and return the index value (using .name
attribute to return the index) of the shifted column:
In [134]:
def func(x):
return df['B'].shift(x['A'])[x.name]
df['C'] = df.apply(lambda x: func(x), axis=1)
df
Out[134]:
A B C
0 1 6 NaN
1 2 7 NaN
2 1 8 7.0
3 2 9 7.0
4 1 10 9.0
这篇关于 pandas 的变迁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文