简体   繁体   中英

Iteratively write rows of pandas dataframe to a CSV file

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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