gpt4 book ai didi

python - 以多 header pandas 数据框为条件

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:35 24 4
gpt4 key购买 nike

我有以下数据框

np.random.seed(0)
header = [np.array(['location','location','location','location2','location2','location2']),
np.array(['S1','S2','S3','S1','S2','S3'])]
df = pd.DataFrame(np.random.randn(5, 6), columns = header )
df

location location2
S1 S2 S3 S1 S2 S3
0 1.764052 0.400157 0.978738 2.240893 1.867558 -0.977278
1 0.950088 -0.151357 -0.103219 0.410599 0.144044 1.454274
2 0.761038 0.121675 0.443863 0.333674 1.494079 -0.205158
3 0.313068 -0.854096 -2.552990 0.653619 0.864436 -0.742165
4 2.269755 -1.454366 0.045759 -0.187184 1.532779 1.469359

我想执行以下计算

['location2']['s1'] * 100 if ['location2']['s2] >= 0

下面的查询没有成功

df['location2']['s1'] = np.where((df["location2"]['S2'] >= 0), df["location2"]['S1'] * 100, df["location2"]['S1'])
df

最佳答案

使用loc,为MultiIndex键指定元组:

df.loc[df.loc[:, ('location2', 'S2')] >=0, ('location', 'S1')] *= 100
df

location location2
S1 S2 S3 S1 S2 S3
0 176.405235 0.400157 0.978738 2.240893 1.867558 -0.977278
1 95.008842 -0.151357 -0.103219 0.410599 0.144044 1.454274
2 76.103773 0.121675 0.443863 0.333674 1.494079 -0.205158
3 31.306770 -0.854096 -2.552990 0.653619 0.864436 -0.742165
4 226.975462 -1.454366 0.045759 -0.187184 1.532779 1.469359

关于python - 以多 header pandas 数据框为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54409660/

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