【问题标题】:pandas: expand strings in a column to substrings and add them to the rowspandas:将列中的字符串扩展为子字符串并将它们添加到行中
【发布时间】:2020-10-15 18:36:33
【问题描述】:

我有一个数据框,其中包含许多 cloumns,每个单元格中有多个字符串,我想获取字符串的子字符串并将它们添加为新数据框中的新列,并在新数据框中添加一个描述第一列的额外列,如下面的例子。我知道如何对原始数据框中的一列执行此操作,但我想一次对所有列执行此操作。

import pandas as pd

data = {'First':  ['First string, second string, third string,...', 'NaN','First string, second string, third string,...'],
    'Second': ['NaN', 'First string, second string, third string,...','First string, second string, third string,...'],
    'third': ['First string, second string, third string,...', 'First string, second string, third string,...','NaN'],
    'forth': ['First string, second string, third string,...', 'NaN','First string, second string, third string,...'],
     ....
    }

df = pd.DataFrame (data, columns = ['First','Second',...])

一栏:

  lst= df['first'].dropna().tolist()

  my_list= [x for xs in lst for x in xs.split(',')]

  df_new = pd.DataFrame(my_list, columns =['text'])

虽然我不确定如何添加与“my_list”大小相同且带有前一列名称的第二列,因此在本例中为“第一”。

一列的期望输出:

 df_new:
    text             name
 0  First string     first
 1  second string    first
 2  third  string    first
    ...              ...

我想要发生的是,来自 df 的所有列都作为行添加到 df_new,而列“名称”的单元格的前列名称对应于第一列字符串。

【问题讨论】:

    标签: python pandas string list multiple-columns


    【解决方案1】:

    我希望这会有所帮助!

    #create the columns as rows 
    df_new = pd.DataFrame({'text':df.T.index})
    df_new['text'] = df_new['text'].str.strip("'")
    #create a new column for group
    df_new['group']=1
    #cumsum the column names 
    df_new['name'] = df_new.groupby('group')['text'].apply(lambda x: (x + ' ').cumsum().str.strip() + ",")
    del df_new['group']
    

    【讨论】:

      猜你喜欢
      • 2020-09-23
      • 1970-01-01
      • 2018-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2022-01-21
      相关资源
      最近更新 更多