pandas 大熊猫可以读取转置的 CSV 文件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39381475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:58:17  来源:igfitidea点击:

Can pandas read a transposed CSV?

pythonpandascsv

提问by ajwood

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

可以pandas读取转置的 CSV 文件吗?这是文件(请注意,我还想选择列的子集):

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

回答by piRSquared

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

回答by Miertz

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

这也将使 df 以您想要的方式结束