【问题标题】:How to remove error like this (cannot perform __mod__ with this index type: Index)?如何删除这样的错误(无法使用此索引类型执行 __mod__:索引)?
【发布时间】:2020-09-08 05:32:19
【问题描述】:

我是 Pandas 和 Numpy 的新手。我在这里尝试做的是采用 Numpy 数组 将它们转换为 pandas DataFrame,从这个 DataFrame 我尝试只使用 奇数行 .iloc 和 lambda ?但它显示错误,如

无法使用此索引类型执行 mod:Index.

你能帮帮我吗?

# Numpy 数组

df= np.arange(25).reshape(5,5)

# 更改为数据框

index = [f'{num}' for num in range(5)]

columnss = list(string.ascii_lowercase[0:5])

df=pd.DataFrame(data=df,columns=columnss,index=index)

#通过索引访问行

df.iloc[lambda x : x.index%2 == 0] 

【问题讨论】:

    标签: python pandas numpy dataframe lambda


    【解决方案1】:

    将索引转换为整数:

    a = df.rename(index=int).iloc[lambda x : x.index%2 == 0]
    print (a)
        a   b   c   d   e
    0   0   1   2   3   4
    2  10  11  12  13  14
    4  20  21  22  23  24
    

    或使用:

    arr = np.arange(25).reshape(5,5)
    #removed converted to strings
    index = range(5)
    columnss = list(string.ascii_lowercase[0:5])
    
    df = pd.DataFrame(arr,columns=columnss,index=index)
    

    如果需要不带整数的索引选择:

    arr = np.arange(25).reshape(5,5)
    
    index = [f'{num}val' for num in range(5)]
    columnss = list(string.ascii_lowercase[0:5])
    df=pd.DataFrame(data=arr,columns=columnss,index=index)
    
    # Accessing the rows via index
    a = df.iloc[lambda x : np.arange(len(x))%2 == 0]
    print (a)
           a   b   c   d   e
    0val   0   1   2   3   4
    2val  10  11  12  13  14
    4val  20  21  22  23  24
    

    【讨论】:

    • @MatrixxHunt - 超级棒!如果我的回答有帮助,请不要忘记accept。谢谢。
    【解决方案2】:

    另一种解决方案是,

    pd.DataFrame(df[::2], columns=list(string.ascii_lowercase[0:5]))
    

    O/P:

        a   b   c   d   e
    0   0   1   2   3   4
    1  10  11  12  13  14
    2  20  21  22  23  24
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      • 2016-11-05
      • 2016-04-03
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 2018-12-30
      相关资源
      最近更新 更多