【问题标题】:Convert 300 CSV files to one 2D Array in python在 python 中将 300 个 CSV 文件转换为一个 2D 数组
【发布时间】:2020-02-18 12:25:29
【问题描述】:

我有大约 300 个 CSV 格式的数据。我想用 Python 将它们转换成二维数组。每个 CSV 文件有一列包含大约 150,000 个条目。 CSV 的头部是标签。 转换成数组后,数组的第一行应该是第一个 CSV 文件,数组的第二行应该是第二个 CSV 文件,以此类推。 最后,我想要一个包含 300 行和 150,000 列的数组。第一列应包含标签。 我希望你能帮我解决这个问题。

非常感谢。

到目前为止,我已经编写了循环遍历包含 csv 文件的文件夹的代码

def CSV_File_Loop(Path_Fil):
    files = [join(Path_File,f) for f in listdir(Path_file) if isfile(join  (Path_File,f) and ".csv" in f]
    for file in files:
        d=pandas.read_csv(file, header = None)

【问题讨论】:

标签: python arrays pandas csv dataframe


【解决方案1】:
dfs = [pd.read_csv(f, header = None) for f in files]
df = pd.concat(dfs,axis=1).T

测试

dfs = [pd.DataFrame(np.random.randn(150000)) for i in range(300)]
df = pd.concat(dfs,axis=1).T
print (df.shape)

输出

(300, 150000)

【讨论】:

  • 非常感谢,它有效。我还有一个小问题,如何将 df 转换为新的 CSV?
  • df.to_csv("thefilename.csv")
猜你喜欢
  • 2018-07-11
  • 2020-12-01
  • 1970-01-01
  • 2014-08-31
  • 2018-02-18
  • 2021-02-19
  • 1970-01-01
  • 2021-11-29
  • 2020-12-30
相关资源
最近更新 更多