Python- pandas -将数据框写入CSV [英] Python - Pandas - Write Dataframe to CSV
问题描述
我正在尝试使用熊猫将4表,3列和50行数据帧文件写入csv.我收到以下错误AttributeError: 'dict' object has no attribute 'to_csv'
.我相信我在正确地编写语法,但是谁能指出我在尝试将数据帧写入csv时语法不正确的地方?
I'm trying to write a 4 table, 3 column, and 50 row dataframe file to a csv using pandas. I'm getting the following error AttributeError: 'dict' object has no attribute 'to_csv'
. I believe I'm writing the syntax correctly, but could anyone point out where my syntax is incorrect in trying to write a dataframe to a csv?
'dict' object has no attribute 'to_csv'
import pandas as pd
import numpy as np
df = pd.read_excel("filelocation.xlsx",
sheetname=['pnl1 Data ','pnl2 Data','pnl3 Data','pnl4 Data'],
skiprows=8, parse_cols="B:D", keep_default_na='FALSE', na_values=['NULL'])
df.to_csv('filelocation.csv', line_terminator=',', index=False, header=False) #error occurs on this line
推荐答案
您的直觉是正确的;代码中的语法没有任何问题.
Your intuition is right; there's nothing wrong with the syntax in your code.
之所以收到AttributeError
,是因为您正在从工作簿中的多张纸上读取数据,从而生成了DataFrames(而不是一个DataFrame)的 dictionary ,然后您尝试从中进行to_csv
(方法仅适用于DataFrame).
You are receiving the AttributeError
because you are reading data from multiple sheets within your workbook, generating a dictionary of DataFrames (instead of one DataFrame), from which you attempt to_csv
(a method only available to a DataFrame).
在编写代码时,您所生成的字典的键与工作表的名称相对应,并且值是各自的DataFrame.在 read_excel()
的文档中对此进行了说明.方法.
As your code is written, the keys of the dictionary you generate correspond to the names of the worksheets, and the values are the respective DataFrames. It's all explained in the docs for the read_excel()
method.
要编写一个包含所有工作表中的汇总数据的csv文件,您可以遍历工作表并将每个DataFrame附加到文件中(如果您的工作表具有相同的结构和尺寸,则可以这样做):
To write a csv file containing the aggregate data from all the worksheets, you could loop through the worksheets and append each DataFrame to your file (this works if your sheets have the same structure and dimensions):
import pandas as pd
import numpy as np
sheets = ['pnl1 Data ','pnl2 Data','pnl3 Data','pnl4 Data']
for sheet in sheets:
df = pd.read_excel("filelocation.xlsx",
sheetname=sheet,
skiprows=8,
parse_cols="B:D",
keep_default_na='FALSE',
na_values=['NULL'])
with open('filelocation.csv', 'a') as f:
df.to_csv(f, line_terminator=',', index=False, header=False)
这篇关于Python- pandas -将数据框写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!