I have a csv file with 15 columns and around 17000 rows. My problem is to search in a specific column (for example: column 'name') for an input string, if it matches, print the the row [i] that contains the string, the previous row [i-1] and the next row [i+1], in order i-1, i, i+1. Repeat the process till the last element of the column (my data file is formated so that it contains no duplicate).
I use this reference to find the rows and the program runs well. Below is my python code:
import pandas as pd
x = input('Please input the name: ')
df = pd.read_csv("input.csv", sep = ",")
idx = df[df.name.str.contains(x, na=False)].index.tolist()
for i in idx:
print(df.iloc[[i-1, i, i+1]])
I would like to ask how to export the filtered data above to a new dataframe and output it to a new csv file? I follow this reference:
df.iloc[[i-1, i, i+1]].to_csv('result.csv', index=True, mode='a')
The output file is ok but it doesn't include the columns' names and I also think that it is not so formal and optimal acording to the author of the topic.
Thank you very much.