简体   繁体   English

Python:通过迭代Pandas Dataframe写入CSV文件

[英]Python: Writing to CSV file from iterating through Pandas Dataframe

I am new to Python. 我是Python的新手。 How can I write to a CSV file while iterating through a DataFrame? 如何在迭代DataFrame时写入CSV文件?

readCSV1 = pd.read_csv(r'ProductDetails1.csv')
df1 = DataFrame(readCSV1)

for index, row in df1.iterrows():
print(index, row['SKU'], row['SKU'],row['Title'],row['Cost'],row['Weight 
    Value'],row['Weight Unit']...............)

I am iterating through a large csv file that contains many columns, however I would like to be able to limit the columns in the final csv file as well as put in other arguments. 我正在迭代包含许多列的大型csv文件,但是我希望能够限制最终csv文件中的列以及放入其他参数。 The print output to the console is correct, however I am having trouble figuring out how best to print this to a new csv file as I will be performing many other functions and do not want to simply edit the dataframe itself. 控制台的打印输出是正确的,但是我无法确定如何最好地将其打印到新的csv文件,因为我将执行许多其他功能,并且不想简单地编辑数据帧本身。

You should not write to the csv file line by line. 您不应该逐行写入csv文件。 It is highly inefficient. 这是非常低效的。 You should instead clean / limit your dataframe to the contents you want to write, and then call pd.DataFrame.to_csv() all at once. 您应该将数据帧清理/限制为要写入的内容,然后一次调用pd.DataFrame.to_csv()

For example: 例如:

df = pd.read_csv(r'ProductDetails1.csv')

#Refine your dataframe here
refined_df = df[['SKU','Title','Close','Weight Value','Weight Unit']]

refined_df.to_csv(r'ProductDetails1.csv', index=False)

I would like to be able to limit the columns in the final csv file as well as put in other arguments. 我希望能够限制最终csv文件中的列以及其他参数。

Don't make these adjustments as you write your CSV file. 编写 CSV文件时不要进行这些调整。 Make the adjustments in the dataframe itself before you export to CSV. 在导出为CSV 之前,请在数据框中进行调整。 Then use the purpose-built pd.DataFrame.to_csv method. 然后使用专门构建的pd.DataFrame.to_csv方法。

For example, you can select specific columns in a specific order before exporting: 例如,您可以在导出之前按特定顺序选择特定列:

df = df[['SKU', 'SKU', 'Title', 'Cost']]
df.to_csv('file.csv', index=False)

To "put in other arguments", make new columns via appropriate logic. 要“放入其他参数”,请通过适当的逻辑创建新列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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