重塑 pandas 以列表为值的数据框

Reshape pandas dataframe which has lists as values

我有一个 pandas 数据框,其中包含列表作为值。我想将此数据框转换为预期结果的格式。数据框太大(100 万行)

import pandas as pd

import numpy as np

df = pd.DataFrame(
      [[['A', 'Second'], [], 'N/A', [6]],
      [[2, 3], [3, 4, 6], [3, 4, 5, 7], [2, 6, 3, 4]]],
      columns=list('ABCD')
      )

df.replace('N/A',np.NaN, inplace=True)

df

    A           B        C          D
0   [A,Second]  []       NaN        [6]
1   [2,3]       [3,4,6] [3,4,5,7]   [2,6,3,4]

预期结果

0 A A
0 A Second
0 D 6
1 A 2
1 A 3
1 B 3
1 B 4
1 B 6
1 C 3
1 C 4
1 C 5
1 C 7
1 D 2
1 D 6
1 D 3
1 D 4

`

您可以使用双 stack:

df1 = df.stack()
df = pd.DataFrame(df1.values.tolist(), index=df1.index).stack()
       .reset_index(level=2,drop=True).reset_index()
df.columns = list('abc')
print (df)
    a  b       c
0   0  A       A
1   0  A  Second
2   0  D       6
3   1  A       2
4   1  A       3
5   1  B       3
6   1  B       4
7   1  B       6
8   1  C       3
9   1  C       4
10  1  C       5
11  1  C       7
12  1  D       2
13  1  D       6
14  1  D       3
15  1  D       4
df.stack().apply(pd.Series).stack().reset_index(2, True) \
  .rename_axis(['a', 'b']).reset_index(name='c')

    a  b       c
0   0  A       A
1   0  A  Second
2   0  D       6
3   1  A       2
4   1  A       3
5   1  B       3
6   1  B       4
7   1  B       6
8   1  C       3
9   1  C       4
10  1  C       5
11  1  C       7
12  1  D       2
13  1  D       6
14  1  D       3
15  1  D       4