【问题标题】:PANDAS to_csv is outputting file without delimitersPANDAS to_csv 正在输出没有分隔符的文件
【发布时间】: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


【解决方案1】:

如果我正确理解了您的问题,您希望保存 f2021 中 FileName 值与 f2016 中的值不同的行。

但我认为你的线路有问题

diffList = [f2021[~f2021.FileName.isin(f2016.FileName)]]

在这一行中,您将包含 f2021 的新行的数据帧存储在列表中,然后将其转换为数据帧。

相反,您应该尝试将此数据框直接导出到 .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')

# Creates a DataFrame with rows that do not match among csvs using the FileName field of both csvs to compare csvs
diffDataFrame = f2021[~f2021.FileName.isin(f2016.FileName)]

#converts data frame to a csv
diffDataFrame.to_csv('G:\\v_wildlife_diff.csv', sep=',', index=False, header=True)

【讨论】:

  • 非常感谢!这行得通。我所做的唯一更改是创建数据框:diff_DataFrame =pd.DataFrame(f2021[~f2021.FileName.isin(f2016.FileName)]) 我还添加了列标题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-05
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
相关资源
最近更新 更多