如何组合大量数据帧?

2024-09-25 08:39:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个文件夹中有许多.txt文件。 例如,每个.txt文件如下所示

FileA = pd.DataFrame({'Id':["a","b","c"],'Id2':["a","b","z"],'Amount':[10, 30,50]})
FileB= pd.DataFrame({'Id':["d","e","f","z"],'Id2':["g","h","i","j"],'Amount':[10, 30,50,100]})
FileC= pd.DataFrame({'Id':["r","e"],'Id2':["o","i"],'Amount':[6,33]})
FileD...

我想提取文件夹中每个数据帧的第一行,然后合并所有数据帧。 下面是我所做的

为了列出txt文件,我做了以下操作

txtfiles = []
for file in glob.glob("*.txt"):
    txtfiles.append(file)  

为了提取第一行并合并它们,我做了如下操作

pd.read_table(txtfiles[0])[:1].append([pd.read_table(txtfiles[1])[:1],pd.read_table(txtfiles[2])[:1]],pd.read_table.......)

如果是txt的数字。文件很小,我可以这样做,但如果有很多.txt文件,我需要一个自动化的方法。 有人知道如何实现自动化吗? 谢谢你的帮助


Tags: 文件数据txt文件夹iddataframereadtable
1条回答
网友
1楼 · 发布于 2024-09-25 08:39:49

基于Sid's answer to this post

input_path = r"insert/your/path" # use the patk where you stored the txt files
all_files = glob.glob(os.path.join(input_path, "*.txt"))     
df_from_each_file = (pd.read_csv(f, nrows=1) for f in all_files)
concatenated_df = pd.concat(df_from_each_file, ignore_index=True)

使用pd.read_csv更新未正确接收文件。用read_table替换read_csv应该会得到预期的结果

input_path = r"insert/your/path" # use the patk where you stored the txt files
all_files = glob.glob(os.path.join(input_path, "*.txt"))     
df_from_each_file = (pd.read_table(f, nrows=1) for f in all_files)
concatenated_df = pd.concat(df_from_each_file, ignore_index=True)

相关问题 更多 >