尝试通过对multindex进行切片并同时考虑列“Z”条件值来设置列“X”值。我可以很容易地设置col'X'值,但是我一直在努力找出条件。你知道吗
import pandas as pd
FOOBAR = (['foo','foo','foo','foo','bar','bar','bar','bar'])
NUM1 = ([5,5,6,6,8,8,5,5])
NUM2 = ([1,1,2,2,3,3,1,1])
NUM3 = ([1001,1002,1002,1002,1003,1004,1004,1005])
#build and name index using data
index = pd.MultiIndex.from_arrays([FOOBAR,NUM1,NUM2,NUM3],
names=['iFOOBAR','iNUM1','iNUM2','iNUM3'])
df = pd.DataFrame({'X': [ 0, 1, 2, 3, 4, 5, 6, 7],
'Y': [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
'Z': [ 1, 2, 2, 4, 5, 6, 7, 7],
'FL': [0.1,0.1,0.2,0.2,0.4,0.4,0.1,0.1]
}, index=index)
df.sortlevel(inplace=True)
idx = pd.IndexSlice
#original df
# FL X Y Z
#iFOOBAR iNUM1 iNUM2 iNUM3
#bar 5 1 1004 0.1 6 G 7
# 1005 0.1 7 H 7
# 8 3 1003 0.4 4 E 5
# 1004 0.4 5 F 6
#foo 5 1 1001 0.1 0 A 1
# 1002 0.1 1 B 2
# 6 2 1002 0.2 2 C 2
# 1002 0.2 3 D 4
#set value in 'X' based on index
newdf = df.loc[idx['foo',5,1,:], idx['X']] = 999
#new df
# FL X Y Z
#iFOOBAR iNUM1 iNUM2 iNUM3
#bar 5 1 1004 0.1 6 G 7
# 1005 0.1 7 H 7
# 8 3 1003 0.4 4 E 5
# 1004 0.4 5 F 6
#foo 5 1 1001 0.1 999 A 1
# 1002 0.1 999 B 2
# 6 2 1002 0.2 2 C 2
# 1002 0.2 3 D 4
#set value in 'X' base on index and 'Z' == 2 ???
#nextdf = df.loc[idx['foo',5,1,:], idx['Z'== 2]], 'X' = 999
#next df: desired output
# FL X Y Z
#iFOOBAR iNUM1 iNUM2 iNUM3
#bar 5 1 1004 0.1 6 G 7
# 1005 0.1 7 H 7
# 8 3 1003 0.4 4 E 5
# 1004 0.4 5 F 6
#foo 5 1 1001 0.1 0 A 1
# 1002 0.1 999 B 2
# 6 2 1002 0.2 2 C 2
# 1002 0.2 3 D 4
如果数据帧
df
具有唯一索引,那么可以使用由于您的
df
没有唯一索引,因此可以创建一个伪索引列,然后以类似方式继续:收益率
请注意,chrisb's solution效率更高,因为它不生成 子数据帧。它准备顺序索引器,然后剪切一次。你知道吗
这其实有点棘手。感觉可能有更好的方法-但这里有一种方法依赖于对索引内部的一点了解-建立一组符合您的标准的位置,然后将所有这些传递给
iloc
。你知道吗试试这个:(一行)
相关问题 更多 >
编程相关推荐