Reputation: 13
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 e.g. "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!
Upvotes: 1
Views: 1133
Reputation: 836
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)
Upvotes: 2