【发布时间】:2020-04-01 19:46:09
【问题描述】:
假设我有两个数据框:
>> df1
0 1 2
0 a b c
1 d e f
>> df2
0 1 2
0 A B C
1 D E F
我怎样才能交错行?即得到这个:
>> interleaved_df
0 1 2
0 a b c
1 A B C
2 d e f
3 D E F
(请注意,我的真实 DF 具有相同的列,但行数不同)。
我尝试过的
灵感来自this question(非常相似,但在列上询问):
import pandas as pd
from itertools import chain, zip_longest
df1 = pd.DataFrame([['a','b','c'], ['d','e','f']])
df2 = pd.DataFrame([['A','B','C'], ['D','E','F']])
concat_df = pd.concat([df1,df2])
new_index = chain.from_iterable(zip_longest(df1.index, df2.index))
# new_index now holds the interleaved row indices
interleaved_df = concat_df.reindex(new_index)
ValueError: cannot reindex from a duplicate axis
最后一次调用失败是因为 df1 和 df2 有一些相同的索引值(我的真实 DF 也是这种情况)。
有什么想法吗?
【问题讨论】: