Python:将列单元格中的每个数组转换为单个字符串

Python:将列单元格中的每个数组转换为单个字符串,python,arrays,pandas,dataframe,type-conversion,Python,Arrays,Pandas,Dataframe,Type Conversion,我的数据框如下所示: df = pd.DataFrame({'col1': [1, 2, 3 ,4 , 5, 6], 'txt': [[2354],[103, 132, 2457],[132, 1476, 6587],[103, 2457],[103, 1476, 2354], np.nan]}) col1 txt 0 1 [2354] 1 2 [103, 132, 2457] 2 3 [132, 147

我的数据框如下所示:

df = pd.DataFrame({'col1': [1, 2, 3 ,4 , 5, 6], 'txt': [[2354],[103, 132, 2457],[132, 1476, 6587],[103, 2457],[103, 1476, 2354], np.nan]})

   col1                txt
0     1             [2354]
1     2   [103, 132, 2457]
2     3  [132, 1476, 6587]
3     4        [103, 2457]
4     5  [103, 1476, 2354]
5     6                NaN
列“txt”在每个单元格中包含一个数组或NaN

现在我想保持dataframe结构的原样,但是数组应该是一个字符串,包含所有元素,用逗号分隔

所需输出(使用字符串而不是数组):

我找到的解决方案对某个专栏不起作用


谢谢。

仅在筛选行中使用列表理解-如果没有缺少值,但也有必要将所有数字列转换为字符串-通过
映射
或在生成器中转换为字符串:

mask = df['txt'].notnull()
df.loc[mask, 'txt'] = [', '.join(map(str, x)) for x in df.loc[mask, 'txt']]
#alternative solution
#df.loc[mask, 'txt'] = df.loc[mask, 'txt'].apply(lambda x: ', '.join(map(str, x)))
#another solution
#df.loc[mask, 'txt'] = [', '.join(str(i) for i in x) for x in df.loc[mask, 'txt']]

print (df)
   col1              txt
0     1             2354
1     2   103, 132, 2457
2     3  132, 1476, 6587
3     4        103, 2457
4     5  103, 1476, 2354
5     6              NaN

一如既往的完美!谢谢!:)
mask = df['txt'].notnull()
df.loc[mask, 'txt'] = [', '.join(map(str, x)) for x in df.loc[mask, 'txt']]
#alternative solution
#df.loc[mask, 'txt'] = df.loc[mask, 'txt'].apply(lambda x: ', '.join(map(str, x)))
#another solution
#df.loc[mask, 'txt'] = [', '.join(str(i) for i in x) for x in df.loc[mask, 'txt']]

print (df)
   col1              txt
0     1             2354
1     2   103, 132, 2457
2     3  132, 1476, 6587
3     4        103, 2457
4     5  103, 1476, 2354
5     6              NaN