我有 4 个 CSV 文件,以 \t
或 tab
作为分隔符。
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 个文件都有相同的 header 。
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.concat
来实现这一点和 DataFrame.pivot_table
:
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)
关于python - 使用 Pandas 合并多个 CSV 文件以创建具有动态 header 的最终 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63816256/