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

问题描述 投票:0回答:1

按模式分割列很容易:

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]

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

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

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

           A         B
    a  b  c    a  b  c
0   1  2  3    4  5  6
1   7  8  9   10 11 12
python pandas
1个回答
2
投票

这是使用df.stackdf.stack的一种方法,使用unstack则有一点帮助:

unstack

swaplevel

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

swaplevel
© www.soinside.com 2019 - 2024. All rights reserved.