【问题标题】:How to turn it an element of a list to a string?如何将列表的元素转换为字符串?
【发布时间】:2021-12-23 05:42:35
【问题描述】:

我在数据框的一列中有这样的列表:

list1 = [[Petitioner Jae Lee,his,he],[]]

list2 = [[lee],[federal officials]]

list3 = [[],[lawyer]]

但我想变成

list1 = ['Petitioner Jae Lee' , 'his','he']
list2 = ['lee' , 'federal officials']]
list3 = ['lawyer']

我想为数据框中的列执行此操作。我该怎么做?

【问题讨论】:

  • 你是如何读取这些数据的?当前的 Pandas 很可能已经默认将其作为字符串引入。在解决不应该成为问题的问题之前,您可能想回到起点。

标签: pandas list dataframe for-loop


【解决方案1】:
list1 = [['Petitioner Jae Lee','his','he'],[]]
list2 = [['lee'],['federal officials']]
list3 = [[],['lawyer']]

flat_list1 = [item for sublist in list1 for item in sublist]
flat_list2 = [item for sublist in list2 for item in sublist]
flat_list3 = [item for sublist in list3 for item in sublist]

print(flat_list1)
print(flat_list2)
print(flat_list3)

【讨论】:

    【解决方案2】:

    使用Series.map 逐行应用逻辑。

    要将子列表连接成一个列表,您可以使用内置的sum 函数

    df['col'] = df['col'].map(lambda list_i : sum(list_i, []))
    

    更好的选择是解压子列表并将它们传递给itertools.chain

    import itertools as it 
    df['col'] = df['col'].map(lambda list_i : list(it.chain(*list_i)))
    

    或者使用嵌套列表推导

    df['col'] = df['col'].map(lambda list_i : [string for sublist in list_i for string in sublist])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      相关资源
      最近更新 更多