强制 pandas .iloc 返回单行数据帧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45990001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:22:29  来源:igfitidea点击:

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

pythonpandasdataframeindexing

提问by Heisenberg

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

出于编程目的,我希望.iloc始终返回一个数据框,即使结果数据框只有一行。如何做到这一点?

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

当前,.iloc当结果只有一行时返回一个系列。例子:

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, .iloccan either return a Series or a Data Frame, forcing me to manually check for this in my code
  • 根据选择的行数,.iloc可以返回一个系列或一个数据框,迫使我在我的代码中手动检查

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

- .loc,另一方面,总是返回一个数据帧,使其pandas自身不一致(错误信息,如评论中指出的那样)

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.

对于 R 用户,这可以通过drop = FALSE, 或使用 tidyverse 的 tibble来完成,默认情况下它总是返回一个数据帧。

回答by Scott Boston

Use double brackets,

使用双括号,

df.iloc[[0]]

Output:

输出:

   a  b
0  1  3

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

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

Short for df.iloc[[0],:]

短缺 df.iloc[[0],:]

回答by cs95

Get row at position ias a DataFrame with iloceither by,

i使用以下iloc任一方式获取位置作为 DataFrame 的行,

Specifying a list of indices of length 1,

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

df.iloc[[i]]  

Or specifying a slice of length 1:

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

df.iloc[i:i+1] 

If you want to access the row by label instead, use loc:

如果要按标签访问行,请使用 loc

df.loc[[x]]

回答by priyankar sinha

please use the below options:

请使用以下选项:

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

or

或者

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