【发布时间】:2020-01-05 15:11:38
【问题描述】:
我有以下具有多索引列的数据框:
df = pd.DataFrame(np.arange(6).reshape(2, 3),
columns=pd.MultiIndex.from_tuples([('foo', 'a'), ('bar', 'a'), ('bar', 'b')]))
foo bar
a a b
0 0 1 2
1 3 4 5
我想分配一个新列 ('foo', 'b') 以便保留索引级别 0 中值的顺序,即结果列应该是 ('foo', 'a'), ('foo', 'b'), ('bar', 'a'), ('bar', 'b'):
expected = pd.DataFrame(
[[0, 10, 1, 2], [3, 11, 4, 5]],
columns=pd.MultiIndex.from_product([['foo', 'bar'], list('ab')]))
foo bar
a b a b
0 0 10 1 2
1 3 11 4 5
以下内容会很好而且直观,但不幸的是assign 不接受位置参数:
df.assign({('foo', 'b'): [10, 11]})
所以我尝试了各种选项,但新列总是附加在末尾:
# using column indexer (appends the new column to the end):
df2 = df.copy()
df2['foo', 'b'] = [10, 11]
print(df2) # columns out of order
print(df2.sort_index(axis=1)) # order of "foo" and "bar" swapped
# using join (appends the new column to the end):
df3 = df.join(pd.DataFrame([10, 11], index=df.index,
columns=pd.MultiIndex.from_tuples([('foo', 'b')])))
print(df3) # columns out of order
# saving index levels beforehand doesn't help because they are sorted:
df4 = df.copy()
columns = df.columns.levels[0] # columns out of order
df4['foo', 'b'] = [10, 11]
df4 = df4[columns]
print(df4) # columns out of order
我可以使用[x[0] for x in df.columns],然后删除重复项(不使用set,因为应该保留顺序),然后使用结果来索引新数据框的列,但这种方法对于这么简单的方法来说感觉太重了任务。
我知道this question 但是那里的答案不保留列顺序。
【问题讨论】:
标签: python python-3.x pandas