在Pandas中使用DataFrame.ix和元组索引 [英] Using DataFrame.ix with a tuple index in Pandas

查看:945
本文介绍了在Pandas中使用DataFrame.ix和元组索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆熊猫代码使用元组作为索引。我最近遇到了使用 DataFrame.ix 访问DataFrame的单个元素的需要,这被元组困惑。似乎认为我的元组是我想要访问的一系列键,而不是我要访问的单个键(这恰好是一个序列)。如何提取一个元组是关键的单个行?



也许这是一个警告,不要在熊猫索引中使用序列,但在我的情况下太晚了。

  import string,pandas as pd,numpy as np 

bar = pd.DataFrame (np.random.random((8,2)))
bar.columns = ['col1','col2']
bar.index = list(string.ascii_lowercase)[:8]
print bar
print bar.iloc [0] .name
print bar.ix [bar.iloc [0] .name]

bar.index = [tuple (8)中的i的列表(string.ascii_lowercase)[i:i + 3])
print bar.iloc [0] .name
print bar.ix [bar.iloc [0 ] .name]#失败与`KeyError:'a'`


解决方案

 在[17]中:bar.ix [[ bar.iloc [0] .name]] 
出[17]:
col1 col2
(a,b,c)0.216689 0.262511
/ pre>

I have a bunch of Pandas code that uses tuples as indices. I've recently come across the need to access an individual element of a DataFrame with DataFrame.ix, which is getting confused by the tuples. It seems to think my tuple is a sequence of keys I want to access, not a single keys (which happens to be a sequence) that I want to access. How can I extract an individual row for which a tuple is the key?

Perhaps this is a cautionary tale not to use sequences in a Pandas index, but in my case it's too late.

import string, pandas as pd, numpy as np

bar = pd.DataFrame(np.random.random((8,2)))
bar.columns = ['col1', 'col2']
bar.index = list(string.ascii_lowercase)[:8]
print bar
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name]

bar.index = [tuple(list(string.ascii_lowercase)[i:i+3]) for i in range(8)]
print bar.iloc[0].name
print bar.ix[bar.iloc[0].name] # Fails with `KeyError: 'a'`

解决方案

You can wrap the tuple in a list to make this work.

In [17]: bar.ix[[bar.iloc[0].name]]
Out[17]: 
               col1      col2
(a, b, c)  0.216689  0.262511

这篇关于在Pandas中使用DataFrame.ix和元组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆