Python 集值多索引
我对蟒蛇和熊猫都是新手 我试图构造一个数据帧,然后用值填充它 我已经构建了我的数据框架Python 集值多索引,python,pandas,multi-index,Python,Pandas,Multi Index,我对蟒蛇和熊猫都是新手 我试图构造一个数据帧,然后用值填充它 我已经构建了我的数据框架 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
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]
熊猫
.14
会有一些。你在做链式作业。你应该使用loc。查看索引文档。非常感谢。我已经浏览了你链接到的文件,这肯定对这个问题有所帮助。谢谢你的快速回复。我做了更多的调查,阅读了你建议的链接。为了只设置一个元素的值(即,对于特定行中的特定列),首先从数据框中选择相关系列(df['a']),然后在该系列上使用loc->df['a']。loc['[21-23','M','[10000-20000')。谢谢@mortysporty的评论!!!您应该回答自己的问题来解释这一点。