簡體   English   中英

切片1行熊貓數據幀時,切片將變成一系列

[英]When slicing a 1 row pandas dataframe the slice becomes a series

為什么當我對僅包含1行的pandas數據框進行切片時,切片會變成pandas系列? 如何保持數據框?

df=pd.DataFrame(data=[[1,2,3]],columns=['a','b','c'])
df
Out[37]: 
   a  b  c
0  1  2  3


a=df.iloc[0]

a
Out[39]: 
a    1
b    2
c    3
Name: 0, dtype: int64

為了避免重新轉換回DataFrame的中間步驟,在建立索引時請使用雙括號:

a = df.iloc[[0]]
print(a)
   a  b  c
0  1  2  3

速度:

%timeit df.iloc[[0]]
192 µs per loop

%timeit df.loc[0].to_frame().T
468 µs per loop

使用to_frame()T進行轉置:

df.loc[0].to_frame()

   0
a  1
b  2
c  3

df.loc[0].to_frame().T

   a  b  c
0  1  2  3

要么

選項#2使用雙括號[[]]

df.iloc[[0]]

   a  b  c
0  1  2  3

或者您可以按索引切片

a=df.iloc[df.index==0]

a
Out[1782]: 
   a  b  c
0  1  2  3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM