简体   繁体   中英

How can I split a csv file into two files based on values in a column in Python?

I have a csv file with 22 columns and X number of rows. How can I split the csv file into 2 separate files depending on what value is in the eg "item_number" column?

So for example, if a row has "1234" or "2345" in the "item_number" column, I want it (the whole row with all its respective columns included) to go into csv_file_1. If a row has "5678" or "6789" in the "item_number" column, I want it to go into csv_file_2.

I want the code to loop over all of the X number of rows in the original input csv file.

So, the output should be two separate csv files sorted depending on specific "item_number" values.

Thank you in advance for your help, and please let me know if more details are needed!

Is this what you are looking for?

import pandas
data = pandas.read_csv('mycsv.csv')


# just make sure to remove the quotation if the numbers are not string
csv2 = data[data['item_number'].isin(['5678','6789'])]
csv1 = data[data['item_number'].isin(['1234','2345']]

csv1.to_csv('csv1.csv', index=False)
csv2.to_csv('csv2.csv', index=False)

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