Python Pandas Dataframe storing next row values

Viewed 245

I am currently new to python data frames and trying to iterate over rows. I want to be able to get values of next 2 rows and store it in the variable. 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'):

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

I want the output as following:

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

Any help is appreciated. Thank you.

2 Answers

Many ways to do it but something simple like this which makes use of Pandas vectorized operations will work,

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

you can simply use iloc property

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)
Related