title: Pandas - Find some specific rows and output the filtered dataframe into a new CSV file
body: <p>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).</p>
  
  <p>I use this <a href="https://stackoverflow.com/questions/41304829/print-next-line-in-pandas-dataframe">reference</a> to find the rows and the program runs well. Below is my python code:</p>
  
  <pre><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]])
  </code></pre>
  
  <p>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 <a href="https://stackoverflow.com/questions/51296758/how-to-write-a-pandas-dataframe-to-csv-file-line-by-line-one-line-at-a-time">reference</a>: </p>
  
  <pre><code>df.iloc[[i-1, i, i+1]].to_csv('result.csv', index=True, mode='a')
  </code></pre>
  
  <p>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.</p>
  
  <p>Thank you very much.</p>