简体   繁体   English

Pandas会自动将行转换为列

[英]Pandas automatically converts row to column

I have a very simple dataframe like so: 我有一个非常简单的数据帧,如下所示:

In [8]: df
Out[8]: 
   A  B  C
0  2  a  a
1  3  s  3
2  4  c  !
3  1  f  1

My goal is to extract the first row in such a way that looks like this: 我的目标是以这样的方式提取第一行:

   A  B  C
0  2  a  a

As you can see the dataframe shape (1x3) is preserved and the first row still has 3 columns. 如您所见,保留了数据框形状(1x3),第一行仍有3列。

However when I type the following command df.loc[0] the output result is this: 但是,当我输入以下命令df.loc[0] ,输出结果如下:

df.loc[0]
Out[9]: 
A    2
B    a
C    a
Name: 0, dtype: object

As you can see the row has turned into a column with 3 rows! 如您所见,该行已变为包含3行的列! (3x1 instead of 3x1). (3x1而不是3x1)。 How is this possible? 这怎么可能? how can I simply extract the row and preserve its shape as described in my goal? 我怎样才能简单地提取行并保持其形状,如我的目标所述? Could you provide a smart and elegant way to do it? 你能提供一种聪明而优雅的方式吗?

I tried to use the transpose command .T but without success... I know I could create another dataframe where the columns are extracted by the original dataframe but this way quite tedious and not elegant I would say ( pd.DataFrame({'A':[2], 'B':'a', 'C':'a'}) ). 我尝试使用transpose命令.T但没有成功......我知道我可以创建另一个数据帧,其中列由原始数据帧提取但这种方式相当繁琐且不优雅我会说( pd.DataFrame({'A':[2], 'B':'a', 'C':'a'}) )。

Here is the dataframe if you need it: 如果需要,这是数据框:

import pandas as pd
df = pd.DataFrame({'A':[2,3,4,1], 'B':['a','s','c','f'], 'C':['a', 3, '!', 1]})

You need add [] for DataFrame : 您需要为DataFrame添加[]

#select by index value
print (df.loc[[0]])
   A  B  C
0  2  a  a

Or: 要么:

print (df.iloc[[0]])
   A  B  C
0  2  a  a

If need transpose Series , first need convert it to DataFrame by to_frame : 如果需要调换Series ,首先需要将其转换成DataFrameto_frame

print (df.loc[0].to_frame())
   0
A  2
B  a
C  a

print (df.loc[0].to_frame().T)
   A  B  C
0  2  a  a

Use a range selector will preserve the Dataframe format. 使用范围选择器将保留Dataframe格式。

df.iloc[0:1]
Out[221]: 
   A  B  C
0  2  a  a

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

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