【问题标题】:Integer based idexing of pandas dataframe大熊猫数据帧的基于整数的索引
【发布时间】:2020-10-04 21:15:00
【问题描述】:

无论数据框是使用其字符串标签还是按位置提供索引,我都试图让我的代码正常工作。

虽然在以下上下文中使用列标签可以正常工作,但我使用整数的尝试到目前为止都失败了。

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

产生错误信息

密钥错误:0

【问题讨论】:

    标签: python pandas dataframe


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2014-04-17
      • 2020-08-22
      • 2017-12-12
      • 2023-01-26
      • 2023-04-02
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      • 2020-05-25
      相关资源
      最近更新 更多