【问题标题】:Multiple csv not being added to pandas多个csv没有被添加到熊猫
【发布时间】:2021-08-07 07:22:39
【问题描述】:

希望你能帮我解决这个问题。

我在 Pandas 中添加多个 CSV 文件时遇到问题。 我有 12 个具有相同列的销售数据文件(每个月一个:Sales_January_2019Sales_February_2019.... 等等,直到 12 月)。

我尝试了以下代码,但似乎无法正常工作,而且索引号应该是连续的,并且不会在每个文件后重置。我尝试了reset_index(),但也没有用。

import pandas as pd
import glob

path = r'C:\Users\ricar\.spyder-py3\data' # my path
all_files = glob.glob(path + "/*.csv")

li = []

for filename in all_files:
    df = pd.read_csv(filename, index_col=0, header=0)
    li.append(df)
df.reset_index(inplace=True)

frame = pd.concat(li, axis=0, ignore_index=True)

df.drop(columns = ['x_t', 'perf'], inplace=True)
print(df)

【问题讨论】:

  • 错误是什么?打印 df 时会发生什么

标签: python pandas spyder


【解决方案1】:

尝试像这样更正您的代码:

import pandas as pd
import glob

path = r'C:\Users\ricar\.spyder-py3\data' # my path
files = glob.glob(path + "/*.csv")

# Make a list of dataframes
li = [pd.read_csv(file, index_col=0, header=0) for file in files]

# Concatenate dataframes and remove useless columns
df = pd.concat(li, axis=0, ignore_index=True)
df.drop(columns=["x_t", "perf"], inplace=True)

print(df)

【讨论】:

    猜你喜欢
    • 2018-07-18
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 2019-07-28
    • 2013-07-06
    相关资源
    最近更新 更多