【发布时间】:2021-11-24 19:15:47
【问题描述】:
我正在使用 pycharm 中的 pandas to_csv() 函数将数据框导出到 csv 文件。但是,导出的文件不包含任何分隔符。该脚本的总体目标是读取两个 csv 文件(一个来自 2016 年,一个来自 2021 年,其中包含一些类似的信息,但 2021 csv 已添加信息),使用名为“文件名”的字段搜索 csv 文件中的不同行, ' 并将与新 csv 文件不同的行写入。这将让我看到自 2016 年以来添加到 csv 的内容。代码一直运行到我将数据框导出到最终 csv 的最终过程。我检查了记事本中的输出,没有出现逗号。
我尝试指定参数以确保文件以逗号分隔,但我相信这应该是默认值。这是我的代码:
#the csv's are large, ~1000 rows so I set the display options manually
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)
# Opens csv files as dataframes
f2016 = pd.read_csv( 'G:\\Wildlife_V_ErikSimoneNico_Done.csv',)
f2021 = pd.read_csv('G:\\test_v_wildlife_output.csv')
# stores files that do not match among csv in a list using the FileName field of both csvs to
# compare csvs
diffList = [f2021[~f2021.FileName.isin(f2016.FileName)]]
#converts list to a dataframe
diffList_df = pd.DataFrame(diffList)
#converts data frame to a csv
diffList_df.to_csv('G:\\v_wildlife_diff.csv', sep=',', index=False, header=True)
【问题讨论】:
-
您能确认
diffList_df有多个列吗?如果您将列表转换为数据框导致所有内容都被压缩到包含一堆数据的单列中,那么它将无法正常工作。df.to_csv应该使用分隔符来分隔df列,所以需要有多个列 -
@scotscotmcc,diffList_df 将所有内容都集中在一列中。我通过使用 columns=[] 手动添加列标题进行检查并收到此错误:“AssertionError:22 列已通过,传递的数据有 1 列。”所以我认为这是问题的根源,但我仍然不确定如何解决它。感谢收看这个!
-
已通过消除创建列表的不必要步骤来解决此问题。谢谢大家!
标签: python pandas dataframe export-to-csv