获取熊猫数据框中的下一个元素

时间:2020-03-22 17:40:24

标签: python pandas list dataframe

假设我有一个索引位置列表:

index_position = [1,3,5]

还有这样的数据框:

df = pd.DataFrame({'A': [0,1,2,3,4,5,6,7,8,9,10]})

我要尝试的是遍历列表,并将df中的元素位置添加到df中的下一个元素位置,方式类似于:

for i in index_position:
    sum = df['A'].iloc[i] + df['A'].iloc[i+1]
    print(sum)

这将导致它打印48。当然,i+1不幸的是没有给我列表中的下一个元素,它确实在元素上加了1。

3 个答案:

答案 0 :(得分:2)

这还不够吗?

Item

答案 1 :(得分:1)

尝试pd.DataFrame.rolling

>>> print(*df.loc[index_position, 'A'].rolling(2).sum().dropna(), sep='\n')
4.0
8.0

对于其他数据:

>>> df = pd.DataFrame({'A': range(0,30,3)})
>>> df
    A
0   0
1   3
2   6
3   9
4  12
5  15
6  18
7  21
8  24
9  27

>>> index_position = [1, 3, 5]

>>> print(*df.loc[index_position,'A'].rolling(2).sum().dropna(), sep='\n')
12.0
24.0

答案 2 :(得分:0)

您可以enumerate遍历列表以获取索引(或连续计数)。

for count, index in enumerate(index_position):
    print('count: ', count)
    print('index: ', index)

这将导致:

>> count: 0
>> index: 1

>> count: 1
>> index: 3

>> count: 2
>> index: 5