简体   繁体   中英

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
pd.read_csv('file.csv', index_col=0, header=None).T

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM