Month: December 2015
Mixed indexing with integer index in Pandas DataFrame
Indexing in Python’s Pandas can at times be tricky. Here is an example with mixed indexing (.ix) with integer index:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pandas as pd | |
df = pd.DataFrame([[1, 2, 's'], [3, 4, 't'], [4, 5, 'u']], | |
index=[-1, 0, 1], columns=['a', 'b', 'c']) | |
>>> df.a # Correct type | |
-1 1 | |
0 3 | |
1 4 | |
Name: a, dtype: int64 | |
>>> df.loc[0, ['a', 'b']] # Wrong indexing | |
a 3 | |
b 4 | |
Name: 0, dtype: object | |
>>> df.ix[0, ['a', 'b']] # Wrong indexing | |
a 3 | |
b 4 | |
Name: 0, dtype: object | |
>>> df.iloc[0, :][['a', 'b']] # Correct indexing, wrong type | |
a 1 | |
b 2 | |
Name: -1, dtype: object | |
>>> df.loc[:, ['a', 'b']].iloc[0, :] # Correct indexing and type, but long | |
a 1 | |
b 2 | |
Name: -1, dtype: int64 | |
>>> df.ix[df.index[0], ['a', 'b']] # Ok | |
a 1 | |
b 2 | |
I ran into the issue when I wanted index with integer for DataFrame representing EEG data in one of its methods