我有一个具有混合索引值的数据集,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?你能在切片中“修复它”吗?更改索引的数据类型是唯一的选择吗?
https://stackoverflow.com/questions/60043045
复制相似问题