Swap rows and columns in CSV files
Transpose CSV
Transposing a CSV file swaps rows and columns. The original rows become columns and the original columns become rows. This operation is commonly used when reshaping datasets for downstream analysis, visualization, or compatibility with specific software tools.
Input:
Gene,Sample1,Sample2
BRCA1,12,18
TP53,25,30
Output:
Gene,BRCA1,TP53
Sample1,12,25
Sample2,18,30
import pandas as pd
df = pd.read_csv("input.csv")
df.T.to_csv(
"transposed.csv",
header=False
)
awk -F',' '{
for (i=1; i<=NF; i++)
a[i,NR]=$i
if (NF>p)
p=NF
}
END {
for (i=1; i<=p; i++) {
for (j=1; j<=NR; j++)
printf "%s%s",
a[i,j],
(j==NR ? RS : ",")
}
}' input.csv > transposed.csv