pandas str 拆分并应用,创建多索引 df

Mor*_*itz 3 python pandas

按模式拆分列很容易:

import pandas as pd

_df = pd.DataFrame([['1 / 2 / 3', '4 / 5 / 6'], ['7 / 8 / 9', '10 / 11 / 12']])
_df.apply(lambda x: x.str.split(' / '))

           0             1
0  [1, 2, 3]     [4, 5, 6]
1  [7, 8, 9]  [10, 11, 12]
Run Code Online (Sandbox Code Playgroud)

但是如何使用多expand=True索引创建数据帧?我不知道我可以在哪里传递索引。

_df.apply(lambda x: x.str.split(' / ', expand=True))
ValueError: If using all scalar values, you must pass an index
Run Code Online (Sandbox Code Playgroud)

预期输出(列名不重要,可以是任意的):

           A         B
    a  b  c    a  b  c
0   1  2  3    4  5  6
1   7  8  9   10 11 12
Run Code Online (Sandbox Code Playgroud)

ank*_*_91 5

这是一种使用方法df.stackunstack并在一些帮助下使用swaplevel

s=_df.stack().str.split(' / ')
out = (pd.DataFrame(s.tolist(),index=s.index).unstack()
      .swaplevel(axis=1).sort_index(axis=1))
Run Code Online (Sandbox Code Playgroud)
   0         1        
   0  1  2   0   1   2
0  1  2  3   4   5   6
1  7  8  9  10  11  12
Run Code Online (Sandbox Code Playgroud)

为了匹配特定的输出,我们可以使用:

from string import ascii_lowercase
out.rename(columns=dict(enumerate(ascii_lowercase)))

   a         b        
   a  b  c   a   b   c
0  1  2  3   4   5   6
1  7  8  9  10  11  12
Run Code Online (Sandbox Code Playgroud)

或者更好:)

from string import ascii_lowercase, ascii_uppercase
out.rename(columns=dict(enumerate(ascii_uppercase)), level=0, inplace=True)
out.rename(columns=dict(enumerate(ascii_lowercase)), level=1, inplace=True)


print(out)

   A         B        
   a  b  c   a   b   c
0  1  2  3   4   5   6
1  7  8  9  10  11  12
Run Code Online (Sandbox Code Playgroud)