无论数据帧是使用其字符串标签还是按位置提供索引,我都试图使我的代码正常工作。
虽然在以下情况下使用列标签可以正常工作,但到目前为止,我使用整数的尝试都失败了。
if(isinstance(person_index, int)):
people['p_series'] = pd.DataFrame(df.iloc[df['ID']==sample][person_index]) # This fails
people['p_series'] = pd.DataFrame(df[df['ID']==sample][person_index]) # This works
我收到错误消息
基于iLocation的布尔索引不能将可索引的内容用作掩码
尝试不使用iloc进行索引
pd.DataFrame(df[df['ID']==sample][person_index])
或使用loc
pd.DataFrame(df.loc[df['ID']==sample][person_index])
产生错误消息
KeyError:0
答案 0 :(得分:1)
我不确定数据框 df
是什么样子,但考虑到例如
import pandas as pd
df = pd.DataFrame({
'ID': [111, 111, 222],
'first_name': ['John', 'Jane', 'Joe'],
'last_name': ['Doe', 'Doe', 'Schmoe']})
print(df)
我们有
ID first_name last_name
0 111 John Doe
1 111 Jane Doe
2 222 Joe Schmoe
那么,
sample=111
person_index=0
print(df[df['ID']==sample])
结果
ID first_name last_name
0 111 John Doe
1 111 Jane Doe
和
print(df[df['ID']==sample].iloc[person_index])
结果
ID 111
first_name John
last_name Doe
Name: 0, dtype: object
但是,如果将 .iloc
移到开头:
print(df.iloc[df['ID']==sample][person_index])
结果与您提到的类似:NotImplementedError: iLocation based boolean indexing on an integer type is not available