[英]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.