简体   繁体   English

如何在python熊猫中切片数组标签?

[英]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)]. 熊猫数据框标签可以是数组,例如代替['a','b','c'],因为我的列为[(0,10),(1,11),(2,12)]。

My array is called df and I only have 2 rows, 0 and 1. 我的数组称为df,我只有2行,即0和1。

I would like to slice the array such that for row 0 I get results for columns (1,11) and (2,12). 我想对数组进行切片,以便为第0行获得列(1,11)和(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 TypeError:无法散列的类型:“列表”或语法错误:无效的语法

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] . 试试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. 也许这些是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: 您可以使用ix方法:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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