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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With