我在 Mac OSX Lion 和 Pandas 0.11.0 上使用 Python 2.7 和 IPython shell。
我有一个简短的问题,使用数据选择方法.isin
.
问题是我想使用 .isin
在项目列表上,所以:
data = df[df[header[0]].isin(list)]
执行此操作时出现以下错误:
KeyError: u'no item named '
我通过调用以前开发的函数来生成初始列表。我尝试使用
eval
在列表中,这似乎解决了使用 raw_input
时出现的问题并迭代其中的项目 - 有点试图解决我在过渡到 IPython
时遇到的一些问题和 Python 2.7
(最初使用 Python 3.3
)。我还尝试遍历列表,首先执行以下操作:
data = df[df[header[0]].isin(list[0])]
但这也会返回:
KeyError: u'no item named '
更新:
这是标题:
Unnamed: 0 9752 non-null values
zipcode 9752 non-null values
xcoord 9752 non-null values
ycoord 9752 non-null values
age_age5064 9752 non-null values
age_age6574 9752 non-null values
age_age75plus 9752 non-null values
sex_female 9752 non-null values
sex_male 9752 non-null values
stage_early 9752 non-null values
stage_late 9752 non-null values
death_death 9752 non-null values
death_not_death 9752 non-null values
access 9752 non-null values
dtypes: float64(2), int64(12)
另外,我有一个用于获取标题的函数,这对我来说更容易,输出如下所示:
['',
'zipcode',
'xcoord',
'ycoord',
'age_age5064',
'age_age6574',
'age_age75plus',
'sex_female',
'sex_male',
'stage_early',
'stage_late',
'death_death',
'death_not_death',
'access']
实际上,现在我考虑了一下,这可能是导致问题的原因-尽管
eval
仍然不会修复它。更新 2:
所以,最初,正如你在上面看到的
.isin
,我用的是 header[0]
,这是不对的。我再次尝试使用 header[1]
,这是合适的。我收到以下错误: TypeError: 'int' object is not iterable
我也再次尝试了常规列表并得到了这个错误:
TypeError: int() argument must be a string or a number, not 'list'
我想,哪个更明确地说明了这个问题......
最佳答案
尝试使用 df.columns 作为标题:
df[df[df.columns[1]].isin(list)]
关于python-2.7 - Python - 列表中的 Pandas '.isin',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16804476/