Forcing pandas .iloc to return a single-row dataframe?

For programming purpose, I want .iloc to consistently return a data frame, even when the resulting data frame has only one row. How to accomplish this?

Currently, .iloc returns a Series when the result only has one row. Example:

In [1]: df = pd.DataFrame({'a':[1,2], 'b':[3,4]})


In [2]: df
Out[2]:
a  b
0  1  3
1  2  4


In [3]: type(df.iloc[0, :])
Out[3]: pandas.core.series.Series

This behavior is poor for 2 reasons:

  • Depending on the number of chosen rows, .iloc can either return a Series or a Data Frame, forcing me to manually check for this in my code

- .loc, on the other hand, always return a Data Frame, making pandas inconsistent within itself (wrong info, as pointed out in the comment)

For the R user, this can be accomplished with drop = FALSE, or by using tidyverse's tibble, which always return a data frame by default.

52471 次浏览

用双括号,

df.iloc[[0]]

产出:

   a  b
0  1  3


print(type(df.iloc[[0]])


<class 'pandas.core.frame.DataFrame'>

df.iloc[[0],:]的简称

按标签访问行: loc

# Setup
df = pd.DataFrame({'X': [1, 2, 3], 'Y':[4, 5, 6]}, index=['a', 'b', 'c'])
df


X  Y
a  1  4
b  2  5
c  3  6

若要获取 DataFrame 而不是 Series,请传递长度为1的索引列表,

df.loc[['a']]
# Same as
df.loc[['a'], :] # selects all columns


X  Y
a  1  4

若要选择多个特定行,请使用

df.loc[['a', 'c']]


X  Y
a  1  4
c  3  6

若要选择连续的行范围,请使用

df.loc['b':'c']


X  Y
b  2  5
c  3  6

按位置访问行: iloc

指定长度为1的索引列表,

i = 1
df.iloc[[i]]


X  Y
b  2  5

或者,指定一个长度为1的片:

df.iloc[i:i+1]


X  Y
b  2  5

To select multiple rows or a contiguous slice you'd use a similar syntax as with loc.

please use the below options:

df1 = df.iloc[[0],:]
#type(df1)
df1

或者

df1 = df.iloc[0:1,:]
#type(df1)
df1

双括号方法并不总是适用于我(例如,当我使用条件选择带有 loc 的时间戳行时)。

但是,您可以将 to_frame()添加到操作中。

>>> df = pd.DataFrame({'a':[1,2], 'b':[3,4]})


>>> df2 = df.iloc[0, :].to_frame().transpose()


>>> type(df2)
<class 'pandas.core.frame.DataFrame'>
single_Sample1=df.iloc[7:10]
single_Sample1

[1] : https://i.stack.imgur.com/RHHDZ.png**strong text * *

从数据帧获取单行提取使用:

df_name.iloc[index,:].to_frame().transpose()