根据Series在DataFrame中设置多个单元格

问题描述 投票:0回答:1

我有一个 Pandas DataFrame,它的构造如下:

=pd.DataFrame(
    [[1, 2, 4], [1, 3, 1], [4, 6, 2]],
    columns=["A", "B", "C"],
    index=["Foo", "Bar", "Baz"],
)
     A  B  C
Foo  1  2  4
Bar  1  3  1
Baz  4  6  2

并且 Series 通过标签指向其中两个单元格:

=pd.Series(data=["Baz", "Foo"], index=["A", "C"])
A    Baz
C    Foo
dtype: object

我想将单元格的值乘以-1,这样我得到的 DF 看起来像:

     A  B  C
Foo  1  2 -4
Bar  1  3  1
Baz -4  6  2

我知道我可以迭代地做到这一点:

for col, index in series:
    df.loc[[index], [col]] = df.loc[[index], [col]] * -1

但是有没有一种衬垫可以以这种方式同时设置多个单元?

pandas
1个回答
0
投票

您可以交叉制表该系列的索引和值,这样您就可以在需要相乘的地方得到一个

1

df = df.mul(1 - 2*pd.crosstab(s, s.index), fill_value=1)
© www.soinside.com 2019 - 2024. All rights reserved.