gpt4 book ai didi

python - 连接单列多个不同形状的文件

转载 作者:行者123 更新时间:2023-12-01 09:08:45 24 4
gpt4 key购买 nike

我有 200 个不同的文件,我需要将它们逐列连接到一个文件中。这 200 个文件位于一个目录中,因此我尝试了以下脚本。

path = '/data' 
files = os.listdir(path)

files_txt = [os.path.join(path,i) for i in files if i.endswith('tsv')]

## Change it into dataframe
dfs = [pd.DataFrame.from_csv(x, sep='\t')[[6]] for x in files_txt]
##Concatenate it
merged = pd.concat(dfs, axis=1)

但它会引发以下值错误,因为每个文件的形状都不同。我想有一些解决方案。谢谢

这里有错误,

ValueError: Shape of passed values is (149, 13864), indices imply (149, 13860)

最佳答案

索引包含重复项,那么concat将会失败,因为它将基于索引来加入数据帧

dfs = [pd.DataFrame.from_csv(x, sep='\t')[[6]].reset_index(drop=True) for x in files_txt]
##Concatenate it
merged = pd.concat(dfs, axis=1)

使用支票

for x in dfs : 
print(x.index.is_unique)

为了重现错误

df1=pd.DataFrame({'A':[1,2]})
df2=pd.DataFrame({'A':[1,2]},index=[1,1])
pd.concat([df1,df2],axis=1)

ValueError: Shape of passed values is (2, 5), indices imply (2, 3)

关于python - 连接单列多个不同形状的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51832622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com