Cut a Pandas dataset with an array of indexes and column names

I want to replicate the behavior of a numpy array using pandas dataframe. I want to pass an array of indexes and column names and get a list of objects that are in the corresponding index and column name.

import pandas as pd
import numpy as np

In numpy:

array=np.array(range(9)).reshape([3,3])
print array
print array[[0,1],[0,1]]

[[0 1 2]
 [3 4 5]
 [6 7 8]]

[0 4]

In pandas:

prng = pd.period_range('1/1/2011', '1/1/2013', freq='A')
df=pd.DataFrame(array,index=prng)
print df

      0  1  2
2011  0  1  2
2012  3  4  5
2013  6  7  8

df[[2011,2012],[0,1]]

Expected Result:

[0 4]

How do I cut this framework so that it returns the same as numpy?

+4
source share
1 answer

Pandas does not support this directly; he could, but the problem is how to indicate that you need coordinates, and not different axes, for example. df.iloc[[0,1],[0,1]]means give me 0 and 1 rows and 0 and 1 column.

, :

,

In [19]: row_indexer = df.index.get_indexer([Period('2011'),Period('2012')])

In [20]: col_indexer = df.columns.get_indexer([0,1])

In [21]: z = np.zeros(df.shape,dtype=bool)

In [22]: z[row_indexer,col_indexer] = True

In [23]: df.where(z)
Out[23]: 
       0   1   2
2011   0 NaN NaN
2012 NaN   4 NaN
2013 NaN NaN NaN

, ( )

In [63]: df.values[[0,1],[0,1]]
Out[63]: array([0, 4])

; ( )

In [26]: df.loc['2011',0]
Out[26]: 0

In [27]: df.loc['2012',1]
Out[27]: 4
+6

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


All Articles