简体   繁体   English

Python Pandas Dataframe 存储下一行值

[英]Python Pandas Dataframe storing next row values

I am currently new to python data frames and trying to iterate over rows.我目前是 python 数据帧的新手,并尝试遍历行。 I want to be able to get values of next 2 rows and store it in the variable.我希望能够获取下 2 行的值并将其存储在变量中。 Following is code snippet:以下是代码片段:

df = pd.read_csv('Input.csv')
for index, row in df.iterrows():
    row_1 = row['Word']
    row_2 = row['Word'] + 1 # I know this is incorrect and it won't work
    row_3 = row['Word'] + 2 # I know this is incorrect and it won't work
    print(row_1, row_2, row_3)

I was hoping that given ('Input.csv'):我希望给定('Input.csv'):

Word <- #Column
 Hi
 Hello
 Some
 Phone
 keys
 motion
 entries

I want the output as following:我想要 output 如下:

Hi, Hello, Some
Hello, Some, Phone
Some, Phone, keys
Phone, keys, motion
keys, motion, entries

Any help is appreciated.任何帮助表示赞赏。 Thank you.谢谢你。

Many ways to do it but something simple like this which makes use of Pandas vectorized operations will work,有很多方法可以做到这一点,但像这样使用 Pandas 矢量化操作的简单方法将起作用,

(df['Word'] + ', ' + df['Word'].shift(-1)+ ', ' + df['Word'].shift(-2)).dropna()

you can simply use iloc property你可以简单地使用iloc属性

df = pd.read_csv('Input.csv')
for index, row in df.iterrows():
    row_1 = df.iloc[index]['word']
    row_2 = df.iloc[index + 1]['word']
    row_3 = df.iloc[index + 2]['word'] 
    print(row_1, row_2, row_3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM