我有以下字符串列。
Str1 Str2 Str3
OK I Go
Yes Hm
Fine I see
我想将它们组合成一个列表变量
AllStr
["ok", "I", "Go"]
["Yes", "Hm"]
["Fine", "I see"]
我尝试了不同的方法,我很接近但不太正确:
df_manual_label['AllStr'] = df_manual_label[['Str1', 'Str2', 'Str3']].apply(lambda x: ', '.join(x.astype(str)), axis=1)
最佳答案
你可以使用stack
df['New']=df.replace('',np.nan).stack().groupby(level=0).apply(list)
df
Out[1666]:
Str1 Str2 Str3 New
0 OK I Go [OK, I, Go]
1 Yes Hm [Yes, Hm]
2 Fine I see [Fine, I see]
关于python - 如何在 Pandas 中将多列合并到一个变量(即一个列表)中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49699678/