我想在选择后交换级别并设置值。
在示例中,我想将“c1”列就地设置为 1,但它似乎没有像我预期的那样工作。
编辑:未明确表达:我想将 1 设置为 C1 列的值。不要重命名 C1.
import numpy as np
import pandas as pd
mix = pd.MultiIndex.from_tuples([('a1','b1','c1'),('a1','b2','c1'),('a1','b3','c2')])
df = pd.DataFrame(np.zeros((3,3)),columns=mix)
print(df)
df.swaplevel(0,2,axis=1).loc[:,'c1']=1
print(df)
Output
a1
b1 b2 b3
c1 c1 c2
0 0.0 0.0 0.0
1 0.0 0.0 0.0
2 0.0 0.0 0.0
' FutureWarning: In a future version, `df.iloc[:, i] = newvals` will attempt \nto set the values inplace instead of always setting a new array. \nTo retain the old behavior, use either `df[df.columns[i]] = newvals` or, \nif columns are non-unique, `df.isetitem(i, newvals)`\n'
swaplevel
+ assign
df.swaplevel(0, 2, axis=1).assign(c1=1)
结果
c1 c2
b1 b2 b3
a1 a1 a1
0 1 1 0.0
1 1 1 0.0
2 1 1 0.0