python如何设置双索引_python – 设置值多索引熊猫

我是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]

这里发生了什么?我对这个想法很开放,我完全误解了多索引的工作原理.任何人?

解决方法:

这将使您获得此解决方案:

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]

标签:python,pandas,multi-index

来源: https://codeday.me/bug/20190517/1119944.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值