Home > Blockchain >  Iteratively write rows of pandas dataframe to a CSV file
Iteratively write rows of pandas dataframe to a CSV file

Time:10-26

I have a CSV file that looks like this:

     state  year  candidate  forecast_prob result  winflag
0  Alabama  2008   Sessions           1.00    Win        1
1  Alabama  2008    Figures           0.00   Lose        0
2  Alabama  2010     Shelby           1.00    Win        1
3  Alabama  2010     Barnes           0.00   Loss        0
4   Alaska  2008     Begich           1.00    Win        1
5   Alaska  2008    Stevens           0.00   Lose        0
6   Alaska  2010     Miller           0.71   Lose        0
7   Alaska  2010  Murkowski           0.21    Win        1
8   Alaska  2010    McAdams           0.08   Loss        0
9  Arizona  2010   Glassman           1.00    Win        1

I've turned this into a Pandas dataframe. How can I write every single row to another CSV file where result = Win?

CodePudding user response:

You can create a new dataframe

new_df = df[df["result"] == "Win"]

And you can write it to csv.

new_df.to_csv("new_df.csv")

  • Related