gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:38:31 25 4
gpt4 key购买 nike

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

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

现在,当我有一个 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

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

SyntaxError: keyword can't be an expression

我可以
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

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

最佳答案

如果我正确阅读本文,它会不会像以下那样简单:

原始 df:

first        bar
second one two
A 0.386729 1.014010
B 0.236824 0.439019
C 0.530020 -0.268751

代码:
df[('bar','one')] *= 10

更新 df(修改列):
first         bar
second one two
A 3.8672946 1.014010
B 2.3682376 0.439019
C 5.3002040 -0.268751

或者,更新 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

关于pandas - 如何在多索引列上使用 Pandas .assign() 方法链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43918488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com