首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果索引的数据类型混合了int/str,则df.loc会生成错误

如果索引的数据类型混合了int/str,则df.loc会生成错误
EN

Stack Overflow用户
提问于 2020-02-04 00:12:06
回答 1查看 112关注 0票数 2

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

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

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

我创建了以下测试用例:

代码语言:javascript
复制
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?你能在切片中“修复它”吗?更改索引的数据类型是唯一的选择吗?

EN

回答 1

Stack Overflow用户

发布于 2020-02-04 01:05:26

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

不需要,您可以使用get_loc来查找标签索引的位置,您可以在iloc[]下使用它

代码语言:javascript
复制
df4.iloc[df4.index.get_loc('b') : df4.index.get_loc(4)+1]

代码语言:javascript
复制
   Col
b   20
3   30
4   10
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60043045

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档