What is the alternative to legacy .ix for label-based mixed selection?

I am trying to select specific rows and columns, but it will not allow me to use .ilocor .loc, because the column names are not integers.

            Madrid  Boston  Tokyo  Shanghai  Kolkota
2014-01-01     -16      22     49       -24       40
2014-01-02     -49      -7     45         2       -6
2014-01-03     -24      41    -22       -11        0
2014-01-04     -28     -14     -2        20       28
2014-01-05     -49      15    -40        -2        3

With .ixI was able to do this:

df.ix[1:5, 'Madrid':'Tokyo']
            Madrid  Boston  Tokyo
2014-01-02     -49      -7     45
2014-01-03     -24      41    -22
2014-01-04     -28     -14     -2
2014-01-05     -49      15    -40

Now that is .ixout of date, what is the alternative?

+4
source share
1 answer

Quick and easy way:

df.loc[df.index[1:5], "Madrid":"Tokyo"]

So for example:

>>> df = pd.DataFrame(np.random.randint(-50,50,(5,5)), index=pd.date_range("2014-01-01", "2014-01-05"), columns=['Madrid', 'Boston', 'Tokyo', 'Shanghai', 'Kolkota'])
>>> df
            Madrid  Boston  Tokyo  Shanghai  Kolkota
2014-01-01     -16      22     49       -24       40
2014-01-02     -49      -7     45         2       -6
2014-01-03     -24      41    -22       -11        0
2014-01-04     -28     -14     -2        20       28
2014-01-05     -49      15    -40        -2        3
>>> df.loc[df.index[1:5], "Madrid":"Tokyo"]
            Madrid  Boston  Tokyo
2014-01-02     -49      -7     45
2014-01-03     -24      41    -22
2014-01-04     -28     -14     -2
2014-01-05     -49      15    -40

You can use the same approach to select specific rows, so if you need rows 0, 2, and 4 (first, third, and fifth):

>>> df.loc[df.index[[0, 2, 4]], "Madrid":"Tokyo"]
            Madrid  Boston  Tokyo
2014-01-01     -16      22     49
2014-01-03     -24      41    -22
2014-01-05     -49      15    -40

Note

Python 2 Python 3, pandas, .ix pandas 0.20.2

+3

Source: https://habr.com/ru/post/1683194/


All Articles