Pandas DataFrame splicing results become rows

I'm wondering if there is a way to keep the pandas dataframe data type after I slice the data.

For example, if I have a pandas DataFrame called df with multiple columns, when I crop one column it is no longer a DataFrame but a series. Is there a way to save it as a data file?

I mean that

type(df)
pandas.core.frame.DataFrame

      

but

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

      

The only way I've decided to work around this is to explicitly override it as a dataframe.

pd.DataFrame(df.iloc[:,0])

      

+3


source to share


2 answers


Indeed, there is:

type(df.iloc[:,[0]])

      



Go to your column / columns as a list and a dataframe is returned. You can see the difference:

In [288]: df = pd.DataFrame({0 : [1, 2, 3], 1: [3, 4, 5], 2:[4, 5, 6]}); df
Out[288]: 
   0  1  2
0  1  3  4
1  2  4  5
2  3  5  6

In [289]: df.iloc[:, 0]
Out[289]: 
0    1
1    2
2    3
Name: 0, dtype: int64

In [290]: df.iloc[:, [0]]
Out[290]: 
   0
0  1
1  2
2  3

In [291]: type(df.iloc[:, [0]])
Out[291]: pandas.core.frame.DataFrame

      

+2


source


I like COLDSPEED's answer, but this is an alternative approach



df.iloc[:, 0].to_frame()

   0
0  1
1  2
2  3

      

+2


source







All Articles