【问题标题】:Splitting multiple columns on a delimiter into rows in pandas dataframe [duplicate]将分隔符上的多列拆分为熊猫数据框中的行[重复]
【发布时间】:2018-10-09 11:34:58
【问题描述】:

我有一个熊猫数据框,如下所示:

id    pos      value                sent
1     a/b/c    test/test2/test3     21
2     d/a      test/test5           21

我想拆分 (=explode)df['pos']df['token'] 以便数据框如下所示:

id      pos          value         sent
1       a            test          21
1       b            test2         21 
1       c            test3         21 
2       d            test          21
2       a            test5         21

如果我拆分每一列然后再将它们连接起来,这将不起作用

pos = df.token.str.split('/', expand=True).stack().str.strip().reset_index(level=1, drop=True)

df1 = pd.concat([pos,value], axis=1, keys=['pos','value'])

有什么想法吗?我真的很感激。

编辑:

我在这里尝试使用此解决方案:https://stackoverflow.com/a/40449726/4219498

但我收到以下错误: TypeError: Cannot cast array data from dtype('int64') to dtype('int32') according to the rule 'safe'

我想这是一个与 numpy 相关的问题,尽管我不确定这是如何发生的。我正在使用 Python 2.7.14

【问题讨论】:

  • 查看以下页面:@piRSquared 的解决方案可以轻松扩展到许多类似情况,例如您所拥有的:stackoverflow.com/questions/49923145/…
  • 同意。这个解决方案很容易扩展并解决了我的问题。

标签: python pandas dataframe split


【解决方案1】:

我倾向于避免使用 stack 魔法,而是倾向于从头开始构建新的数据框。这通常也更有效。下面是一种方法。

import numpy as np
from itertools import chain

lens = list(map(len, df['pos'].str.split('/')))

res = pd.DataFrame({'id': np.repeat(df['id'], lens),
                    'pos': list(chain.from_iterable(df['pos'].str.split('/'))),
                    'value': list(chain.from_iterable(df['value'].str.split('/'))),
                    'sent': np.repeat(df['sent'], lens)})

print(res)

   id pos  sent  value
0   1   a    21   test
0   1   b    21  test2
0   1   c    21  test3
1   2   d    21   test
1   2   a    21  test5

【讨论】:

    猜你喜欢
    • 2021-02-02
    • 1970-01-01
    • 2016-09-16
    • 1970-01-01
    • 2018-12-04
    • 2019-12-28
    • 2016-12-03
    • 2023-03-21
    • 2018-10-17
    相关资源
    最近更新 更多