使用Pandas合并多个CSV文件,以创建带有动态标题的最终CSV文件

2024-09-30 14:28:25 发布

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

我有4个CSV文件,其中\ttab作为分隔符

alok@alok-HP-Laptop-14s-cr1:~/tmp/krati$ for file in sample*.csv; do echo $file; cat $file; echo ; done
sample1.csv
ProbeID p_code  intensities
B1_1_3  6170    2
B2_1_3  6170    2.2
B3_1_4  6170    2.3
12345   6170    2.4
1234567 6170    2.5

sample2.csv
ProbeID p_code  intensities
B1_1_3  5320    3
B2_1_3  5320    3.2
B3_1_4  5320    3.3
12345   5320    3.4
1234567 5320    3.5

sample3.csv
ProbeID p_code  intensities
B1_1_3  1234    4
B2_1_3  1234    4.2
B3_1_4  1234    4.3
12345   1234    4.4
1234567 1234    4.5

sample4.csv
ProbeID p_code  intensities
B1_1_3  3120    5
B2_1_3  3120    5.2
B3_1_4  3120    5.3
12345   3120    5.4
1234567 3120    5.5

所有4个文件都有相同的标题

ProbeID在所有文件中都是相同的,顺序也是相同的。每个文件在单个CSV文件中都有相同的p_code

我必须以这种格式将所有这些CSV文件合并成一个

alok@alok-HP-Laptop-14s-cr1:~/tmp/krati$ cat output1.csv 
ProbeID 6170    5320    1234    3120
B1_1_3  2       3       4       5
B2_1_3  2.2     3.2     4.2     5.2
B3_1_4  2.3     3.3     4.3     5.3
12345   2.4     3.4     4.4     5.4
1234567 2.5     3.5     4.5     5.5

在此输出文件中,列是基于p_code值动态的

我可以用字典轻松地做到这一点。如何使用Pandas生成这样的输出


Tags: 文件csvcodeb2tmpb1filehp
1条回答
网友
1楼 · 发布于 2024-09-30 14:28:25

我们可以使用^{}^{}实现这一点:

import os
import pandas as pd

df = pd.concat(
    [pd.read_csv(f, sep="\t") for f in os.listdir() if f.endswith(".csv") and f.startswith("sample")], 
    ignore_index=True
)

df = df.pivot_table(index="ProbeID", columns="p_code", values="intensities", aggfunc="sum")
print(df)

相关问题 更多 >