Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas DataFrame spliced results become series

I am wondering if there is a way to preserving pandas dataframe datatype after I slice the data.

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

What I mean is that

type(df)
pandas.core.frame.DataFrame

but

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

Only way I figured of getting around it is to explicitly redefine it as a dataframe.

pd.DataFrame(df.iloc[:,0])
like image 942
pandas_get_good Avatar asked Oct 14 '25 07:10

pandas_get_good


2 Answers

Indeed there is:

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

Pass in 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
like image 117
cs95 Avatar answered Oct 16 '25 22:10

cs95


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

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

   0
0  1
1  2
2  3
like image 24
piRSquared Avatar answered Oct 16 '25 21:10

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!