【问题标题】:How to split a data frame of strings into multiple columns based on a list of indexes with pandas?如何根据带有熊猫的索引列表将字符串数据框拆分为多列?
【发布时间】:2020-03-22 02:43:43
【问题描述】:

我有一个由字符串组成的数据框,我想根据索引列表将每个字符串拆分为多个列。我尝试过使用 str.extract 方法并且成功了,但我想知道是否有有效的方法来做到这一点(例如,传递索引列表)

df = pd.DataFrame(['100000037031061620140520173', '200002823676010220150420181','200004493595011020150720181'])
df2_test = df[0].str.extract('(.{6})(.{6})(.{8})(.{6})(.{1})') #i'd like to pass the list of positions to split into columns
positions = [6,6,8,6,1]

【问题讨论】:

  • 位置是否定义了对每个字符串进行拆分的索引?
  • 没错@Shaunak Sen
  • 您要寻找的预期输出是什么?
  • 我正在寻找与使用 str.extract (df2_test) 相同的输出,但我不想手动输入位置,而是传递一个列表,其中包含拆分所在的索引制作。

标签: python pandas


【解决方案1】:

如果你喜欢没有正则表达式,我们可以使用series.str.slice()

idx= [0] + [*np.cumsum(positions)]
#[0, 6, 12, 20, 26, 27]
slices = [(a,b) for a,b in zip(idx,idx[1:])]
#[(0, 6), (6, 12), (12, 20), (20, 26), (26, 27)]
pd.concat([df[0].str.slice(*i).rename(e) for e,i in enumerate(slices)],axis=1)

        0       1         2       3  4
0  100000  037031  06162014  052017  3
1  200002  823676  01022015  042018  1
2  200004  493595  01102015  072018  1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 2019-04-21
    • 1970-01-01
    • 2016-11-16
    • 2021-07-27
    • 2019-05-17
    • 2018-07-26
    相关资源
    最近更新 更多