我有以下
df1 = pd.DataFrame({'data': [1,2,3]})
df2 = pd.DataFrame({'data': [4,5,6]})
df = pd.concat([df1,df2], keys=['hello','world'], axis=1)
在df['world']['data']*2
列中创建新的嵌套列(例如hello
)的“正确”方法是什么?我已经尝试过df['hello']['new_col'] = df['world']['data']*2
,但这似乎不起作用。
答案 0 :(得分:1)
使用tuple
进行选择和设置MultiIndex
:
df[('hello','new_col')] = df[('world','data')]*2
print (df)
hello world hello
data data new_col
0 1 4 8
1 2 5 10
2 3 6 12
不建议像df['world']['data']
那样选择-link,因为可能会链接索引。