如何在多索引列上使用 Pandas .assign() 方法链?

Lit*_*les 5 method-chaining multi-index pandas

对于单级索引列,我会执行以下操作

arrays = [['one', 'two', ]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(pd.np.random.randn(3, 2), index=['A', 'B', 'C'], columns=index)
print(df)


first   one two
A   0.919921    -1.407321
B   1.100169    -0.927249
C   -0.520308   0.619783

print(df.assign(one=lambda x: x.one * 100))

first   one         two
A       144.950877  0.633516
B       -0.593133   -0.630641
C       -5.661949   -0.738884
Run Code Online (Sandbox Code Playgroud)

现在,当我有一个 MultiIndex 列时,我可以使用访问所需的列,.loc但我无法将其分配给任何内容,因为它出现了错误SyntaxError: keyword can't be an expression

这是一个例子,

arrays = [['bar', 'bar'],
          ['one', 'two']]

tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second'])
df = pd.DataFrame(pd.np.random.randn(3, 2), index=['A', 'B', 'C'], columns=index)

print(df)

first   bar
second  one         two
A       1.119243    0.819455
B       -0.473354   -1.340502
C       0.150403    -0.211392
Run Code Online (Sandbox Code Playgroud)

然而,

df.assign(('bar', 'one')=lambda x: x.loc[:, ('bar', 'one')] * 10)

SyntaxError: keyword can't be an expression
Run Code Online (Sandbox Code Playgroud)

我可以

df.assign(barOne=lambda x: x.loc[:, ('bar', 'one')] * 10)


first   bar                     barOne
second  one         two 
A       0.433909    0.949701    4.339091
B       0.011486    -1.395144   0.114858
C       -0.289821   2.106951    -2.89821
Run Code Online (Sandbox Code Playgroud)

但这是不可取的。我想保持我的方法链很好,但也保持 MultiIndexed 列。

elP*_*tor 1

如果我没看错的话,事情会不会这么简单:

原始 df:

first        bar
second       one       two
A       0.386729  1.014010
B       0.236824  0.439019
C       0.530020 -0.268751
Run Code Online (Sandbox Code Playgroud)

代码:

df[('bar','one')] *= 10
Run Code Online (Sandbox Code Playgroud)

更新了 df (修改列):

first         bar
second        one       two
A       3.8672946  1.014010
B       2.3682376  0.439019
C       5.3002040 -0.268751
Run Code Online (Sandbox Code Playgroud)

或者,更新 df (创建新列):

df[('bar','new')] = df[('bar','one')] * 10

first        bar
second       one       two       new
A       0.386729  1.014010  3.867295
B       0.236824  0.439019  2.368238
C       0.530020 -0.268751  5.300204
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的,因为它做了我想要的事情,但不是我想要的方式。正如我上面提到的,我想使用 allocate() 方法,这样我就可以在一个长方法链中做一些事情。不过谢谢。 (3认同)