Forcing pandas.iloc to return a single-line data frame?

For programming purposes, I want the .ilocdata frame to be returned sequentially, even if the resulting data frame has only one row. How to do it?

Currently .ilocreturns a series when the result has only 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 bad for two reasons:

  • Depending on the number of rows selected, it .ilocmay return a Series or Data Frame, forcing me to manually check this in my code

- .loc, on the other hand, always return the Data Frame, making it pandasincompatible inside itself (incorrect information, as indicated in the comment)

R drop = FALSE tidyverse tibble, .

+4
2

,

df.iloc[[0]]

:

   a  b
0  1  3

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

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

df.iloc[[0],:]

+6

.

df.iloc[0:1]

.

   a  b
0  1  3
+2

Source: https://habr.com/ru/post/1684852/


All Articles