[英]Setting a pandas sub dataframe indexed with a MultiIndex
I have a pandas.DataFrame
with a Multi such as: 我有一个带有Multi的pandas.DataFrame
,例如:
In [298]: pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 1})
Out[298]:
x
a 1 1
2 1
b 1 1
3 1
When i want to reassign a sub dataframe ie ( df.loc['a']
), i get a weird output: 当我想重新分配一个子数据帧,即( df.loc['a']
)时,我得到一个奇怪的输出:
In [300]: df.loc['a'] = df.loc['a']
In [301]: df
Out[301]:
x
a 1 NaN
2 NaN
b 1 1
3 1
The example is simple, i obviously intent to have a reassignment more complicated. 这个例子很简单,我显然希望重新分配更复杂。
Is it normal? 这是正常的吗? How can i reassign a sub dataframe indexed with a MultiIndex? 如何重新分配使用MultiIndex索引的子数据帧?
You can use [[..]]
(update the DataFrame rather than the Series): 您可以使用[[..]]
(更新DataFrame而不是Series):
In [11]: df
Out[11]:
x
a 1 1
2 1
b 1 1
3 1
In [12]: df2 = pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 2})
In [13]: df.loc[["a"]] = df2.loc[["a"]]
In [14]: df
Out[14]:
x
a 1 2
2 2
b 1 1
3 1
You can use pd.IndexSlice
to represent slices of a pd.MultiIndex
您可以使用pd.IndexSlice
来表示的片pd.MultiIndex
df.loc[pd.IndexSlice['a', :], :] = 2
print df
a 1 2
2 2
b 1 1
3 1
Other examples 其他例子
df = pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 1})
df.loc[pd.IndexSlice[:, 1], :] = 9
print df
x
a 1 9
2 1
b 1 9
3 1
Or 要么
df = pd.DataFrame(index=pd.MultiIndex.from_tuples([['a', 1], ['a', 2], ['b', 1], ['b', 3]]), data={'x': 1})
df.loc[pd.IndexSlice['b', 3], :] = 31415
print df
x
a 1 1
2 1
b 1 1
3 31415
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.