python - 使用 Pandas 从多个文件构建矩阵

标签 python python-2.7 pandas

在具有 2 列的目录中有多个文件 (20),例如

transcript_id value
ENMUST001     2
ENMUST003     3
ENMUST004     5

每个文件的行数不同我想做的是以这种方式将所有 20 个文件合并到一个巨大的矩阵中

transcript_id value_file1 value_file2....value_file20
ENMUST001     2  3 
ENMUST003     3  4
ENMUST004     5  0

从 transcript_id 列中收集所有 id 和每个文件中的相应值(文件名作为列名),如果没有值则使用 0。

我尝试使用 Pandas 来做到这一点,

import os
import glob
import pandas as pd
path = 'pathtofiles'
transFiles = glob.glob(path + "*.tsv")
df_files = []
for file in transFiles:
    df = pd.read_csv(file, sep='\t')
    df.set_index('transcript_id')
    df_files.append(df)
df_combine = pd.concat(df_files, axis=1).fillna(0) 

Error:
ValueError: No objects to concatenate

想知道非 Pandas 方法是否是更好的方法?感谢任何伪代码。

编辑

找到输出

df.set_index('transcript_id')
print (df.shape)

    (921, 1)
    (1414, 1)
    (659, 1)
    (696, 1)
    (313, 1)
print (df.is_unique)
    (921, 1)
False
(1414, 1)
False
(659, 1)
False
(696, 1)
False
(313, 1)
False
df = df.drop_duplicates(inplace=True)
df_files.append(df)
df_combine = pd.concat(df_files, axis=1).fillna(0)

New error
ValueError: All objects passed were None

重复打印

before:  (921, 1)
after:  (914, 1)
before:  (1414, 1)
after:  (1410, 1)
before:  (659, 1)
after:  (658, 1)
before:  (696, 1)
after:  (694, 1)
before:  (313, 1)
after:  (312, 1)

最佳答案

set_index 的默认行为是 inplace=False。尝试将 df.set_index('transcript_id') 替换为 df = df.set_index('transcript_id')。您还可以使用 df = df[~df.index.duplicated(keep='first')] 删除索引中的重复值。

import os
import glob
import pandas as pd

path = 'pathtofiles'
transFiles = glob.glob(path + "*.tsv")
df_files = []
for file in transFiles:
    df = pd.read_csv(file, sep='\t')
    df = df.set_index('transcript_id') # set index
    df = df[~df.index.duplicated(keep='first')] # remove duplicates
    df.columns = [os.path.split(file)[-1]] # set column name to filename
    df_files.append(df)
df_combine = pd.concat(df_files, axis=1).fillna(0) 

关于python - 使用 Pandas 从多个文件构建矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45524189/

相关文章:

python - 使用pygame旋转图像

python - 权限被拒绝在 linux 中使用 shebang 行运行 python 脚本

python - 使用 python pandas 读取已拆分为多行的行

python - 按季度对 pandas 数据框进行分组以进行绘图

python - 如何在水平布局中调整小部件的大小

Python 2.7 csv 格式不正确

mysql - django runserver 给出 libmysqlclient_18 文件 libmysqlclient.so.18 中未定义的错误

python - Pandas:连接和重新索引数据帧

python - 告诉 PyCharm 代码生成类的字段

python - 由于 __init__ 构造函数而产生的 Pytest 集合警告