python - 如何在 Pandas 中将多列合并到一个变量(即一个列表)中

标签 python pandas variables dataframe merge

我有以下字符串列。

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/

相关文章:

python - 如何使用 OpenCV 和 Python 的蒙版(或透明度)在图像中查找模板?

python - 当我有大量数组时检查重复数组

python - pd.Series.str.lower.replace ('str' , 'replace_str' ) 不起作用但 pd.Series.str.replace。 ('STR' , 'replace_str' ) 呢?

python-3.x - df.describe 和 df.describe() 之间的区别

python - Python中的此Unbound Local错误是什么意思?

python - 数据集在 Pandas 数据框中每月有多少天有记录?

c - 如何限制 C 中另一个进程或函数使用(写/读)文件的访问?

javascript - 如果属性不是赋值语句的一部分,JavaScript 会计算属性的值吗?

javascript - 使用 jQuery/JavaScript 声明只使用一次的变量是否会更慢?

javascript - 在 jupyter 笔记本中加载外部 javascript 库