【问题标题】:Python splitting text in a columnPython 在列中拆分文本
【发布时间】:2017-11-24 14:49:17
【问题描述】:

将列中的文本拆分为 DataFrame 中的多行

df = pd.DataFrame({'age':['34','22','19'],'Ticket':['23:44:55','66:77:88','43:68:05 56:34:12'],'PlusOne':['0','0','1'],})

拆分第三行的两个值

ticket_series = df['Ticket'].str.split(' ').apply(pd.Series, 1).stack()

摆脱堆栈: 降低关卡与DataFrame对齐

ticket_series.index = ticket_series.index.droplevel(-1)
ticketdf = pd.DataFrame(ticket_series)
del df['Ticket']
df.join(ticketdf)
df

不明白为什么不能连在一起!!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你已经接近了,DataFrame构造函数不是必须的,只需要name of Series作为列名:

    ticket_series = df['Ticket'].str.split(' ').apply(pd.Series, 1).stack()
    ticket_series.index = ticket_series.index.droplevel(-1)
    ticket_series.name = 'new'
    

    Series的另一种解决方案:

    ticket_series = (df['Ticket'].str.split(expand=True)
                                 .stack()
                                 .reset_index(level=1, drop=True)
                                 .rename('new'))
    
    print (ticket_series)
    0    23:44:55
    1    66:77:88
    2    43:68:05
    2    56:34:12
    Name: new, dtype: object
    
    
    print (df.drop('Ticket', 1).join(ticket_series).reset_index(drop=True))
      PlusOne age       new
    0       0  34  23:44:55
    1       0  22  66:77:88
    2       1  19  43:68:05
    3       1  19  56:34:12
    

    【讨论】:

    • 如果我只想将 3:68:05 和 56:34:12 这 2 个数据分成两行怎么办?
    • 不确定是否理解。你能解释更多吗?
    • 我不明白为什么我的代码不能将两个数据框连接在一起
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多