gpt4 book ai didi

python - 使用多重索引时 Pandas 的行为非常奇怪

转载 作者:行者123 更新时间:2023-12-01 07:37:44 25 4
gpt4 key购买 nike

我使用以下代码创建具有多索引的 Pandas DataFrame 并更新一些值。

indices = pd.MultiIndex.from_product(iterables=[['X','Y','Z'],['h1','h2','h3']],names=['idx1','idx2'])
df = pd.DataFrame(0.0,index=indices,columns=['A'])

df.loc['X','A']['h1'] = 1.1
df.loc['Y','A']['h1'] = 2.2
df.loc['Z','A']['h1'] = 3.3

print(df)

此代码按预期生成以下输出:

             A
idx1 idx2
X h1 1.1
h2 0.0
h3 0.0
Y h1 2.2
h2 0.0
h3 0.0
Z h1 3.3
h2 0.0
h3 0.0

但是当我使用以下代码时(注意第一个索引中的“Y”移到了末尾),输出是错误的:

import pandas as pd
indices = pd.MultiIndex.from_product(iterables=[['X','Z','Y'],['h1','h2','h3']],names=['idx1','idx2'])
df = pd.DataFrame(0.0,index=indices,columns=['A'])

df.loc['X','A']['h1'] = 1.1
df.loc['Y','A']['h1'] = 2.2
df.loc['Z','A']['h1'] = 3.3

print(df)
             A
idx1 idx2
X h1 0.0
h2 0.0
h3 0.0
Z h1 0.0
h2 0.0
h3 0.0
Y h1 0.0
h2 0.0
h3 0.0

我的第二个代码有什么问题?我正在做一些非常愚蠢的事情,或者这是某种预期的行为?

我尝试过 python 3.7.1 和 3.6.8,两种情况下都使用 pandas 0.23.4。

最佳答案

MultiIndex中使用元组设置值以避免 chained indexing :

df.loc[('X','h1'),'A'] = 1.1
df.loc[('Y','h1'),'A'] = 2.2
df.loc[('Z','h1'),'A'] = 3.3

print(df)
A
idx1 idx2
X h1 1.1
h2 0.0
h3 0.0
Z h1 3.3
h2 0.0
h3 0.0
Y h1 2.2
h2 0.0
h3 0.0

关于python - 使用多重索引时 Pandas 的行为非常奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901613/

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