【问题标题】:Split multiple times?多次拆分?
【发布时间】:2019-01-31 06:22:40
【问题描述】:

所以我目前正在将 txt 文件传输到 csv 中。它大部分都被清理了,但即使在拆分之后,我的一些数据之间仍然存在空列。

下面是我凌乱的 CSV 文件 这是我当前的代码:

Sat_File = '/Users'
output = '/Users2'
import csv
import matplotlib as plt
import pandas as pd
with open(Sat_File,'r') as sat:
    with open(output,'w') as outfile:
        if "2004" in line:
            line=line.split('  ')
            writer=csv.writer(outfile)
            writer.writerow(line)

基本上,我只是想消除我提供的 CSV 图片中的列之间的空白。谢谢!

【问题讨论】:

  • 你进口了熊猫。当pandas.read_csv() 比它好得多时,你为什么还要使用 CSV 阅读器?
  • 尝试使用 line.split() 而不是 line.split(' ')。
  • 老实说,目前只是缺乏专业知识。对 python 来说非常新,对 Pandas 包来说甚至更新。不过我会尝试 pandas.read_csv() !如果可行,我会和你一起回来!
  • @Kantal 好吧,你做得怎么样,那行得通。谢谢!

标签: python pandas csv matplotlib


【解决方案1】:

您可以使用 python Pandas 库来清除空列:

import pandas as pd
df = pd.read_csv('path_to_csv_file').dropna(axis=1, how='all')
df.to_csv('path_to_clean_csv_file')

基本上我们:

  1. 导入 pandas 库。
  2. 将 csv 文件读入一个名为 df 的变量(代表数据框)。 比我们使用允许丢弃空列/行的 dropna 函数。 axis=1 表示删除列(0 表示行),how='all' 表示删除列中的所有值都是空的。
  3. 我们将干净的数据框 df 保存到一个新的干净的 csv 文件中。

$$$ Pr0f!t $$$

【讨论】:

    猜你喜欢
    • 2019-04-15
    • 1970-01-01
    • 2016-04-20
    • 2011-09-20
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多