【问题标题】:df.loc produces an error if the dtype of the index is mixed int/str如果索引的 dtype 混合为 int/str,则 df.loc 会产生错误
【发布时间】:2020-05-19 10:25:37
【问题描述】:

我有一个包含混合索引值 int 和 str 的数据集,df.to_csv 将其读取为对象。

如果我尝试对行进行切片,这不起作用,我会收到 TypeError。

我知道我可以通过更改索引 dtype 来解决这个问题,但我想了解为什么会发生这种情况,或者是否有不同的方式来分割这些混合 dtype 索引?

我创建了以下测试用例:

import os
import pandas as pd
import numpy as np
#all str index
df1 = pd.DataFrame({'Col': [0, 20, 30, 10]}, index=['a', 'b','c','d'])
#all int index
df2 = pd.DataFrame({'Col': [0, 20, 30, 10]}, index=[1, 2, 3, 4])
#all str index with numbers
df3 = pd.DataFrame({'Col': [0, 20, 30, 10]}, index=['a', 'b', '3', '4'])
#mixed str/int
df4 = pd.DataFrame({'Col': [0, 20, 30, 10]}, index=['a', 'b', 3, 4 ])

df1.loc['b':'d']
    Col
b   20
c   30
d   10

df2.loc[2:4]
Col
2   20
3   30
4   10

df3.loc['b':'4']
Col
b   20
3   30
4   10

df4.loc['b':4]

TypeError

df4.index = df4.index.map(str)
df4.loc['b':'4']
Col
b   20
3   30
4   10

为什么切片不适用于 df4? 你能在切片内“修复”它吗? 改变索引的数据类型是唯一的选择吗?

【问题讨论】:

    标签: python pandas dataframe pandas-loc


    【解决方案1】:

    改变索引的数据类型是唯一的选择吗?

    不,您可以使用get_loc 来实现此目的,它会找到标签索引的位置,您可以在iloc[] 下使用:

    df4.iloc[df4.index.get_loc('b') : df4.index.get_loc(4)+1]
    

       Col
    b   20
    3   30
    4   10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 2015-06-10
      • 2017-02-08
      • 2023-02-15
      • 1970-01-01
      • 2016-10-22
      • 2015-10-31
      • 2019-11-02
      相关资源
      最近更新 更多