【发布时间】: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