簡體   English   中英

使用 Pandas 合並多個 CSV 文件以創建帶有動態標題的最終 CSV 文件

[英]Merge multiple CSV files using Pandas to create final CSV file with dynamic header

我有 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值動態的。

我可以使用字典在Python 中輕松完成此操作。 如何使用Pandas生成這樣的輸出?

我們可以使用pandas.concatDataFrame.pivot_table來實現這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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM