【问题标题】:Save a list as a list in a Pandas dataframe column将列表另存为 Pandas 数据框列中的列表
【发布时间】:2020-01-15 06:50:30
【问题描述】:

我正在尝试在数据框中连接 2 个(字符串)列 'col1' 和 'col2',将连接的字符串标记化并将结果列表另存为另一个新列 'result'。

期望的输出:

col1              col2          result
apples bananas    oranges       ['apples','bananas','oranges']
mangoes           apples        ['mangoes','apples']

我正在这样做:

df['result'] = df['col1'].str.cat(df['col2'],sep=" ")
df['result'] = df.result.apply(lambda result: list(re.split(r'\W+', result)))

但我得到这个作为输出:

col1              col2          result
apples bananas    oranges       [apples,bananas,oranges]
mangoes           apples        [mangoes,apples]

我该如何解决这个问题?

【问题讨论】:

    标签: python-3.x pandas dataframe concatenation list-comprehension


    【解决方案1】:

    我认为您的解决方案很好,如果两列都由字符串填充,也可以使用Series.str.split

    '' 不只显示。

    print (df[['col1','col2']].iloc[0].apply(type))
    col1     <class 'str'>
    col2     <class 'str'>
    Name: 0, dtype: object
    
    df['result'] = df['col1'].str.cat(df['col2'],sep=" ").str.split()
    print (df)
                 col1     col2                      result
    0  apples bananas  oranges  [apples, bananas, oranges]
    1         mangoes   apples           [mangoes, apples]
    

    如果第一列由列表填充,第二列由字符串填充:

    print (df[['col1','col2']].iloc[0].apply(type))
    col1    <class 'list'>
    col2     <class 'str'>
    Name: 0, dtype: object
    
    df['result'] = df['col1'] + df['col2'].str.split()
    

    【讨论】:

    • cat() 函数后无法使用 str
    • @PythonNewbie - 你可以试试df['result'] = df['col1'] + df['col2']df['result'] = df['col1'] + df['col2'].str.split() 吗?
    • 没用 :( 我认为是因为 col1 和 col2 中的数据
    • @PythonNewbie - print (df[['col1','col2']].iloc[0].apply(type)) 是什么?
    【解决方案2】:

    这行得通:

    您可以通过以下代码关联您的数据框对象:

    import pandas as pd
    
    list1= ['Apple Banana','Mangos']
    list2= ['Orange','Apples']
    
    dataframe=pd.DataFrame(data=[list1,list2],columns=['Col1','Col2'])
    
    concat_result= list(dataframe['Col1'] +" " + dataframe['Col2']) # concatenate both the columns and convert that into a list type and store it in concat_result label
    
    new_List=[]  #Create new label type list so we can append values.
    final_list=[] #Final object which will contain single quoted String.
    
    for item in concat_result:   #Loop through the list and append the elements after splitting default space. 
        new_List.append(item.split())
    
    
    for new in new_List:   #new_List has two child list, so iterate over them
        for_single_quote=[]
        for inner_list_string in new:  # child List elements
            for_single_quote.append("'%s'" %inner_list_string)
        final_list.append(for_single_quote)
    
    dataframe['result']= final_list
    

    然后最后在数据框中添加新行并分配列表:

    dataframe['result']= final_list
    

    您将获得预期的输出。

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 1970-01-01
      • 2017-06-22
      • 2017-08-29
      • 2018-02-05
      • 2019-03-23
      • 2016-09-29
      • 1970-01-01
      • 2021-08-21
      相关资源
      最近更新 更多