【问题标题】:Merge two lists that are in two columns in a dataframe合并数据框中两列中的两个列表
【发布时间】:2022-02-03 16:19:06
【问题描述】:

我有一个这样的数据框:

worker_codes                  Capacity      new_codes
[24751454, 24751454]          2             [17425801, 74730846]

其中 worker_code 和 new_codes 是两个有 id 的列表,容量是 worker_code 的长度。我想要的是这样的:

list_of_codes                  capacity
[17425801, 74730846, 24751454] 3

所以要合并两个列表,删除重复项并将新容量设置为新列表的长度。我该怎么做?

【问题讨论】:

标签: python-3.x pandas list dataframe merge


【解决方案1】:

您可以将列表加在一起得到一个联合列表,然后转换为set(然后再转换回list)以去除重复项:

df['list_of_codes']  = (df['worker_codes'] + df['new_codes']).apply(set).apply(list)
df['Capacity'] = df['list_of_codes'].apply(len)
df[['list_of_codes','Capacity']]

输出:


    list_of_codes                   Capacity
0   [17425801, 24751454, 74730846]  3

【讨论】:

  • 忘了提到列表是字符串,如何将它们转换为列表?因为否则它会失败。
【解决方案2】:

用途:

df = pd.DataFrame({'worker_codes':   [[24751454, 24751454]], 'Capacity': [2], 'new_codes': [[17425801, 74730846]]})
output = {'list_of_codes':[], 'capacity': []}
for i, row in df.iterrows():
    temp = row['worker_codes']
    temp.extend(row['new_codes'])
    temp = set(temp)
    output['list_of_codes'].append(temp)
    output['capacity'].append(len(temp))
new_df = pd.DataFrame(output)

实际上,您需要合并不同列的值,然后将它们添加到字典中,然后该字典将用于创建新的 df。输出:

【讨论】:

  • 忘了提到列表是字符串,如何将它们转换为列表?因为否则它会失败。
  • 从字符串格式中获取样本。它们的格式是否为 s = '[123, 567]'?然后使用 [x.strip() for x in s[1:-1].split(',')]
猜你喜欢
  • 2019-09-19
  • 2018-05-20
  • 1970-01-01
  • 2017-01-20
  • 2019-05-04
  • 1970-01-01
  • 2020-10-16
  • 2019-10-27
相关资源
最近更新 更多