gpt4 book ai didi

python - 设置值多索引 Pandas

转载 作者:太空狗 更新时间:2023-10-29 20:58:52 25 4
gpt4 key购买 nike

我是 Python 和 Pandas 的新手。

我正在尝试构建一个数据框,然后用值填充它。

我已经构建了我的数据框

from pandas import *

ageMin = 21
ageMax = 31
ageStep = 2

bins_sumins = [0, 10000, 20000]
bins_age = list(range(ageMin, ageMax, ageStep))
indeks_sex = ['M', 'F']
indeks_age = ['[{0}-{1})'.format(bins_age[i-1], bins_age[i]) for i in range(1, len(bins_age))]
indeks_sumins = ['[{0}-{1})'.format(bins_sumins[i-1], bins_sumins[i]) for i in range(1, len(bins_sumins))]
indeks = MultiIndex.from_product([indeks_age, indeks_sex, indeks_sumins], names=['Age', 'Sex', 'Sumins'])

cols = ['A', 'B', 'C', 'D']

df = DataFrame(data = 0, index = indeks, columns = cols)

目前一切顺利。我能够为一整套值赋值

>>> df['A']['[21-23)']['M'] = 1
>>> df
A B C D
Age Sex Sumins
[21-23) M [0-10000) 1 0 0 0
[10000-20000) 1 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[23-25) M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[25-27) M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[27-29) M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0

但是,只设置一个位置的值是不行的...

>>> df['B']['[21-23)']['M']['[10000-20000)'] = 2
>>> df
A B C D
Age Sex Sumins
[21-23) M [0-10000) 1 0 0 0
[10000-20000) 1 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[23-25) M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[25-27) M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[27-29) M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[16 rows x 4 columns]

这是怎么回事?我对我完全误解了多重索引的工作原理的想法持开放态度。有人吗?

最佳答案

首先,查看 chained indexing 上的文档

其次,阅读这篇关于needing to sort MultiIndices的文章.

这会让你得到这个解决方案:

In [46]: df = df.sort_index()

In [47]: df.loc['[21-23)', 'M', '[10000-20000)'] = 2

In [48]: df
Out[48]:
A B C D
Age Sex Sumins
[21-23) F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
M [0-10000) 0 0 0 0
[10000-20000) 2 2 2 2
[23-25) F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[25-27) F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
[27-29) F [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0
M [0-10000) 0 0 0 0
[10000-20000) 0 0 0 0

[16 rows x 4 columns]

pandas .14 会有一些 additional ways for slicing a MultiIndex .

关于python - 设置值多索引 Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108889/

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