在pandas中使用浮点数作为MultiIndex的索引器
我有一个数据表(DataFrame),它的索引是由(p,t)这样的元组组成的,其中p和t都是小数。当我试图通过切片选择某个特定的p值时(用到idx=IndexSlice
),我遇到了以下错误:
df.loc[idx[1.5,:]]
/usr/local/lib/python2.7/dist-packages/pandas-0.14.0rc1-py2.7-linux-x86_64.egg/pandas/core/index.py:496:
FutureWarning: scalar indexers for index type MultiIndex should be integers and not floating point
有没有办法解决这个问题呢?
输入的数据表:
Pump Time
10.0 -10.60 0.000005
-10.59 0.000031
-10.58 0.000007
-10.57 -0.000020
-10.56 -0.000000
-10.55 0.000005
-10.54 -0.000013
-10.53 -0.000049
-10.52 -0.000031
-10.51 -0.000041
-10.50 0.000022
-10.49 -0.000045
-10.48 -0.000070
-10.47 -0.000025
-10.46 0.000002
...
-0.05 4.05 0.000610
6.05 0.000443
8.05 0.000318
10.05 0.000380
12.05 -0.000063
14.05 0.000578
16.05 0.000236
18.05 0.000472
20.05 0.001628
40.05 0.000243
60.05 0.000426
80.05 0.000361
100.05 0.000693
120.05 0.000478
140.05 0.000398
Name: p1Up, Length: 4400, dtype: float64
想要的输出结果:
Pump Time
-0.05 4.05 0.000610
6.05 0.000443
8.05 0.000318
10.05 0.000380
12.05 -0.000063
14.05 0.000578
16.05 0.000236
18.05 0.000472
20.05 0.001628
40.05 0.000243
60.05 0.000426
80.05 0.000361
100.05 0.000693
120.05 0.000478
140.05 0.000398
运行df.info()时出现:
MultiIndex: 4400 entries, (10.0, -10.6) to (-0.05, 140.05)
Data columns (total 1 columns):
p1Up 4400 non-null float64
dtypes: float64(1)
这个数据表是通过在一个循环中拼接而成的,这个循环遍历了不同的p值:
time = (extracted from a file)
lb = [(p,t) for t in time]
ind = pd.MultiIndex.from_tuples(lb, names=['Pump','Time'])
col = ['p1Up','p1Down']
data = np.concatenate((p1up,p1down),axis=1)
# Build dataframes
temp = pd.DataFrame(data, index=ind, columns=col)
df = pd.concat([df,temp])
2 个回答
0
我不知道这是不是太晚了,或者语法有没有变化,但 df.xs(1.5)
可以做到这一点,而且默认情况下会删除你选择的那个层级。我觉得你甚至不需要对它进行排序。不过它只能获取数据,不能用来设置数据。
2