简体   繁体   中英

How do I slice array labels in python pandas?

pandas dataframe labels can be arrays, eg instead of ['a', 'b', 'c'] as columns I have [(0,10), (1,11), (2,12)].

My array is called df and I only have 2 rows, 0 and 1.

I would like to slice the array such that for row 0 I get results for columns (1,11) and (2,12).

Using

a.loc[0,[(1,11)]:[(2,12)]] 

or

a.loc[0,[(1,11):(2,12)]] 

don't seem to work, with various errors such as

TypeError: unhashable type: 'list' or Syntax Error: Invaid Syntax

Any alternative suggestions?

I am very new to this, so please be gentle in case I am being an idiot.

Thanks for your help

Try a[[(1, 11), (2, 12)]].loc[0] .

I don't think there is any way to ask for a slice of tuples, but you can specify a complete list of them.

In general, having tuples as column labels is inconvenient. Perhaps these are part of a MultiIndex. I would advise only using that as a last resort, if there is so simpler way to organize your data.

You can use ix method:

>>> df = pd.DataFrame(np.random.randn(2, 4), 
...           columns=[(0,1),(2,3),(3,4),(5,6)], 
...           index=list('ab'))
>>> df.ix['a', 1:3]
(2, 3)   -0.17856
(3, 4)    0.34741
Name: a, dtype: float64
>>> df.ix['a', [(0,1), (2,3)]]
(0, 1)    0.567471
(2, 3)   -0.178560
Name: a, dtype: float64

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM