如何根据 Python 中一列中的值将一个 csv 文件拆分为两个文件?
How can I split a csv file into two files based on values in a column in Python?
我有一个包含 22 列和 X 行数的 csv 文件。如何根据例如中的值将 csv 文件拆分为 2 个单独的文件“item_number”列?
因此,例如,如果一行在“item_number”列中有“1234”或“2345”,我希望它(包含所有相应列的整行)进入 csv_file_1。如果一行在“item_number”列中有“5678”或“6789”,我希望它进入 csv_file_2.
我希望代码遍历原始输入 csv 文件中的所有 X 行。
因此,输出应该是根据特定“item_number”值排序的两个单独的 csv 文件。
预先感谢您的帮助,如果需要更多详细信息,请告诉我!
这是您要找的吗?
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)
我有一个包含 22 列和 X 行数的 csv 文件。如何根据例如中的值将 csv 文件拆分为 2 个单独的文件“item_number”列?
因此,例如,如果一行在“item_number”列中有“1234”或“2345”,我希望它(包含所有相应列的整行)进入 csv_file_1。如果一行在“item_number”列中有“5678”或“6789”,我希望它进入 csv_file_2.
我希望代码遍历原始输入 csv 文件中的所有 X 行。
因此,输出应该是根据特定“item_number”值排序的两个单独的 csv 文件。
预先感谢您的帮助,如果需要更多详细信息,请告诉我!
这是您要找的吗?
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)