【问题标题】:Extra commas at beginning and end of csv rows, how to remove?csv行开头和结尾的多余逗号,如何删除?
【发布时间】:2017-12-31 12:37:17
【问题描述】:

所以我有一个 .csv 文件,其中每一行如下所示:

,11:00:14,4,5.,93.7,0.01,0.0,7,20,0.001,10,49.3,0.01, ,11:00:15,4,5.,94.7,0.04,0.5,7,20,0.005,10,49.5,0.04,

什么时候应该是这样的:

11:00:14,4,5.,93.7,0.01,0.0,7,20,0.001,10,49.3,0.01 11:00:15,4,5.,94.7,0.04,0.5,7,20,0.005,10,49.5,0.04

我认为这就是 pandas 没有正确创建数据帧的原因。如何删除这些逗号?

生成原始csv文件的代码是

def tsv2csv():

# read tab-delimited file
with open(file_location + tsv_file,'r') as fin:
    cr = csv.reader(fin, delimiter='\t')
    filecontents = [line for line in cr]

# write comma-delimited file (comma is the default delimiter)
# give the exact location of the file
#"newline=''" at the end of the line stops there being spaces between each row
with open(new_csv_file,'w', newline='') as fou:
    cw = csv.writer(fou, quotechar='', quoting=csv.QUOTE_NONE)
    cw.writerows(filecontents)

【问题讨论】:

  • 生成原始CSV文件的代码是什么?
  • 我已经在主帖中添加了代码
  • 如果您的问题得到解答,请vote on, and accept the most helpful one。您可以通过单击最有帮助的答案旁边的灰色复选标记并将其变为绿色来接受答案。谢谢。

标签: python pandas csv dataframe comma


【解决方案1】:

您可以使用usecols 指定要导入的列,如下所示:

import pandas as pd

csv_df = pd.read_csv('temp.csv', header=None, usecols=range(1,13))

这将跳过第一个和最后一个空列。

【讨论】:

  • 这会出现“ValueError:Usecols 与名称不匹配”。恐怕我对 pandas 有点陌生,所以我不确定这是否容易解决
  • 它适用于我,你提供的 csv 样本,可能真实文件不同?
  • 是的,这只是它的一小部分,因为前 15 行左右是用户信息
  • 如果你有header,试着去掉header选项,重要的是usecols。
【解决方案2】:

尾随逗号对应于缺失数据。在加载数据框时,它们会以 NaN 的形式加载,因此您需要做的就是摆脱它,使用 dropna 或将它们切片 -

df = pd.read_csv('file.csv', header=None).dropna(how='all', axis=1)

或者,

df = pd.read_csv('file.csv', header=None).iloc[:, 1:-1]

df

         1   2    3     4     5    6   7   8      9   10    11    12
0  11:00:14   4  5.0  93.7  0.01  0.0   7  20  0.001  10  49.3  0.01
1  11:00:15   4  5.0  94.7  0.04  0.5   7  20  0.005  10  49.5  0.04

【讨论】:

  • 很高兴我做了一个 iloc 解决方案。这是我想说的最通用的。
【解决方案3】:

您可以使用strip 去除文本开头和结尾的任何字符,并给出一个包含您不想转义的字符的字符串作为参数。

x = ',11:00:14,4,5.,93.7,0.01,0.0,7,20,0.001,10,49.3,0.01,'
print x.strip(',')
>11:00:14,4,5.,93.7,0.01,0.0,7,20,0.001,10,49.3,0.01

【讨论】:

    【解决方案4】:

    不确定它是否适用于您的情况,您是否尝试过导入:

        df = pd.read_csv('filename', sep=';')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-08
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2018-05-12
      相关资源
      最近更新 更多