ajwood
ajwood

Reputation: 19057

Can pandas read a transposed CSV?

Can pandas read a transposed CSV? Here's the file (note I'd also like to select a subset of columns):

A,x,x,x,x,1,2,3
B,x,x,x,x,4,5,6
C,x,x,x,x,7,8,9

Would like to get this DataFrame:

   A  B  C
0  1  4  7
1  2  5  8
2  3  6  9

Upvotes: 23

Views: 23317

Answers (2)

Miertz
Miertz

Reputation: 71

In addition, if your file looks like this:

"some-line-you-want-to-skip"
A,x,x,x,x,1,2,3
B,x,x,x,x,4,5,6
C,x,x,x,x,7,8,9

It is possible to do the following:

df = pd.read_csv(filename, skiprows=1, header=None).T   # Read csv, and transpose
df.columns = df.iloc[0]                                 # Set new column names
df.drop(0,inplace=True)                                 # Drop duplicated row

This will also end up with the df looking the way you want

Upvotes: 4

piRSquared
piRSquared

Reputation: 294546

pd.read_csv('file.csv', index_col=0, header=None).T

Upvotes: 35

Related Questions