【发布时间】:2020-10-14 00:13:27
【问题描述】:
我有一段看似简单的代码,但不知何故它不起作用。代码的目标是在文件夹中查找所有泡菜数据,将 for 循环中的第一个作为 pandas 数据框加载,该数据框在以前不存在的变量下命名,如果变量存在,则应加载剩余的泡菜文件作为 pandas 并将它们附加到第一个循环中新创建的 pandas 数据帧:
import pandas as pd
import os
# Creating the first Dataframe using dictionary
df1 = pd.DataFrame({"a":[1, 2, 3, 4],
"b":[5, 6, 7, 8]})
# Creating the Second Dataframe using dictionary
df2 = pd.DataFrame({"a":[1, 2, 3],
"b":[5, 6, 7]})
df1.append(df2)
打印效果很好:
a b
0 1 5
1 2 6
2 3 7
3 4 8
0 1 5
1 2 6
2 3 7
但是,当我尝试在 for 循环中附加存储的 pickle 文件中的数据帧时,它不会打印错误,但它仅适用于第一个数据帧:
df1.to_pickle("DF1.pkl")
df2.to_pickle("DF2.pkl")
files = [f for f in os.listdir('.') if os.path.isfile(f)]
#The line above should produce the line below
files=["DF1.pkl", "DF2.pkl"]
for i in files:
if ".pkl" in i:
if "ALL_DATA" not in globals():
ALL_DATA=pd.read_pickle(i)
else:
ALL_DATA.append(pd.read_pickle(i))
只打印:
a b
0 1 5
1 2 6
2 3 7
3 4 8
谁能帮我澄清一下?
【问题讨论】:
标签: python pandas for-loop append pickle