将包含列表中的列表的数据框列合并到类似索引的新列组合中



给定数据框架:

import pandas as pd
df = pd.DataFrame()
list1 = [['Smith', 'Johnson', 'David'], ['Perry', 'Windler']]
list2 = [['C', 'SF', 'PG'], ['SF', 'SG']]
list3 = [['Injured', 'Injured', 'Not Injured'], ['Not Injured', 'Injured']]
df['list1'] = list1
df['list2'] = list2
df['list3'] = list3

我需要组合创建一个新的列'list4'与这些内容:

list4 = list4 = [[['Smith - C - Injured'], ['Johnson - SF - Injured'], ['David - PG - Not Injured']], [['Perry - SF - Not Injured'], ['Windler - SG - Injured']]]
0 [[Smith - C - Injured], [Johnson - SF - Injured], [David - PG - Not Injured]]
1 [[Perry - SF - Not Injured], [Windler - SG - Injured]]

listcomp:

df["list4"] = [[[f"{l1} - {l2} - {l3}"] for l1, l2, l3 in zip(*lists)]
for lists in df[["list1", "list2", "list3"]].to_numpy()]

输出:

print(df["list4"])
                                                                      
     list4
0  [[Smith - C - Injured], [Johnson - SF - Injured], [David - PG - Not Injured]]
1                         [[Perry - SF - Not Injured], [Windler - SG - Injured]]
df['list4'] = 
[['%s - %s - %s'%(a, b, c) for a, b, c in zip(list1[i], list2[i], list3[i])] 
for i in range(len(df))]
print(df)
list1  ...                                              list4
0  [Smith, Johnson, David]  ...  [Smith - C - Injured, Johnson - SF - Injured, ...
1         [Perry, Windler]  ...  [Perry - SF - Not Injured, Windler - SG - Inju...
[2 rows x 4 columns]

最新更新