问题描述
我在熊猫上有一个df
I have a df in pandas
import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
我想遍历df中的行.对于每一行,我都希望row s value and next row
的值诸如此类(无效):
I want to iterate over rows in df. For each row i want rows value and next row
s valueSomething like(it does not work):
for i, row in df.iterrows():
print row['value']
i1, row1 = next(df.iterrows())
print row1['value']
因此,我想要
'AA'
'BB'
'BB'
'CC'
'CC'
*Wrong index error here
在这一点上,我有解决这个问题的混乱方法
At this point i have mess way to solve this
for i in range(0, df.shape[0])
print df.irow(i)['value']
print df.irow(i+1)['value']
有没有更有效的方法来解决此问题?
Is there more efficient way to solve this issue?
推荐答案
首先,您的混乱方式"是可以的,在数据帧中使用索引没有任何问题,这不会太慢. iterrows()本身并不快.
Firstly, your "messy way" is ok, there's nothing wrong with using indices into the dataframe, and this will not be too slow. iterrows() itself isn't terribly fast.
第一个可行的想法是:
row_iterator = df.iterrows()
_, last = row_iterator.next() # take first item from row_iterator
for i, row in row_iterator:
print(row['value'])
print(last['value'])
last = row
第二种方法可以做类似的事情,将一个索引保存到数据框中:
The second method could do something similar, to save one index into the dataframe:
last = df.irow(0)
for i in range(1, df.shape[0]):
print(last)
print(df.irow(i))
last = df.irow(i)
当速度至关重要时,您可以随时尝试并设置代码时间.
When speed is critical you can always try both and time the code.
这篇关于iterrows大 pandas 获取下一行值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!