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

标签 python pandas concatenation

我有 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/

相关文章:

python - 创建一个Numpy FFT带通滤波器

python - 在 Mac 上安装加密时的 pycrypto massup

python - 遍历每列中的值

python - Python 中的 Pandas 和 NumPy+SciPy 有什么区别?

python - 循环遍历 1 个数据帧并将结果添加到另一个数据帧

使用 ## 和 __LINE__ 创建 C 宏(与定位宏的标记串联)

python - pymysql 只需选择值并保存到变量中

python - SKlearn Tfidfvectorizer 与 Keras : expected dense_input_1 to have shape

audio - ffmpeg 剪切和连接单个命令行

php - 使用 CONCAT 从子查询返回多个值