交织来自 2 个 dfs panda 的行

Interweave rows from 2 dfs panda

我有 2 个 df,我想将这 2 个 df 的行交织在一起以构建 1 个 df。

import pandas as pd
df1 = pd.DataFrame({'SONY': [1,3,5,7,9],}, index=['a','b','c','d','e'])
df1 = pd.DataFrame({'SONY': [2,4,6,8,10],}, index=['a','b','c','d','e'])

预期输出

   SONY
a   1
a   2
b   3
b   4
c   5
c   6
d   7
d   8
e   9
e   10

我失败的尝试,我正在考虑遍历 dfs 并提取行并将它们放入列表中,然后从中构建一个 df。

dfs=[]
numofrows = len(df.index)
for x in range(0, numofrows):
    dfs.append(pd.concat([df1.iloc[x], df2.iloc[x]], ignore_index=True))

我为什么要这样做:我试图在图表后面复制一个 df,这就是它的样子。

你应该让索引不一样,然后使用zip, numpy.hstack, pandas.concat and DataFrame.reindex:

import numpy as np

# Change indices
df1.index+='1'
df2.index+='2'

order = np.hstack(list(zip(df1.index, df2.index)))
df = pd.concat([df1, df2]).reindex(order)
print(df)

[出局]

    SONY
a1     1
a2     2
b1     3
b2     4
c1     5
c2     6
d1     7
d2     8
e1     9
e2    10