简体   繁体   English

Pandas:如何将行转置为列?

[英]Pandas: How to transpose a row to a column?

I have a csv file that I get from a specific software.我有一个从特定软件获得的 csv 文件。 In the csv file there are 196 rows, each row has a different amount of values.在 csv 文件中有 196 行,每行有不同数量的值。 The values are seperated by a semicolon.这些值用分号分隔。

I want to have all values of the dataframe in one column, how to do it?我想在一列中包含 dataframe 的所有值,该怎么做?

dftest = pd.read_csv("test.csv", sep=';', header=None)
dftest
    0
0   14,0;14,0;13,9;13,9;13,8;14,0;13,9;13,9;13,8;1...
1   14,0;14,0;13,9;14,0;14,0;13,9;14,0;14,0;13,8;1...
2   13,8;13,9;14,0;13,9;13,9;14,6;14,0;14,0;13,9;1...
3   14,5;14,4;14,2;14,1;13,9;14,1;14,1;14,2;14,1;1...
4   14,1;14,0;14,1;14,2;14,0;14,3;13,9;14,2;13,7;1...
5   14,5;14,1;14,1;14,1;14,5;14,1;13,9;14,0;14,1;1...
6   14,1;14,7;14,0;13,9;14,2;13,8;13,8;13,9;14,8;1...
7   14,7;13,9;14,2;14,7;15,0;14,5;14,0;14,3;14,0;1...
8   13,9;13,8;15,1;14,1;13,8;14,3;14,1;14,8;14,0;1...
9   15,0;14,4;14,4;13,7;15,0;13,8;14,1;15,0;15,0;1...
10  14,3;13,8;13,9;14,8;14,3;14,0;14,5;14,1;14,0;1...
11  14,5;15,5;14,0;14,1;14,0;13,8;14,2;14,0;15,9;1...

The output looks like this, I want to have all values in one column output 看起来像这样,我想在一列中包含所有值

I would like to make it look like this:我想让它看起来像这样:

0 14,0
1 14,0
2 13,9
.
.
.

If there is only one column 0 with values splitted by ;如果只有一列0的值被; use Series.str.split with DataFrame.stack :使用Series.str.splitDataFrame.stack

df = dftest[0].str.split(';', expand=True).stack().reset_index(drop=True)

you can also use numpy ravel and convert this to 1D Array.您还可以使用 numpy ravel 并将其转换为一维数组。

df = pd.read_csv("test.csv", sep=';', header=None)
df = pd.DataFrame(df.values.ravel(), columns=['Name'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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