Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force .ix to return a DataFrame in pandas

Tags:

python

pandas

When I use .ix with a DataFrame, is there any way to force pandas to always return a DataFrame?

For example, if I run the following lines,

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(6).reshape(3, 2), index=[0, 0, 1])
x = df.ix[0]
y = df.ix[1]

then x will be a DataFrame, because 0 appears twice in the index, and y will be a Series, because 1 is unique in the index. I want y to be a DataFrame too (because I'm using iterrows(), which isn't defined for Series, on the result).

I can check the type of whatever .ix returns and convert it to a DataFrame if needed, but I thought there'd be a better way.

Note: As of Pandas v0.20, .ix indexer is deprecated in favour of .iloc / .loc.

like image 472
hahdawg Avatar asked May 15 '14 20:05

hahdawg


1 Answers

Yes, index it with a list:

> x = df.ix[[0]]
> y = df.ix[[1]]
> type(x)
pandas.core.frame.DataFrame
> type(y)
pandas.core.frame.DataFrame
like image 73
U2EF1 Avatar answered Sep 20 '22 10:09

U2EF1