python - 合并包含列表的数据框列

标签 python pandas dataframe

我有一个包含列表的数据框:

id  rl
a   [c,v,b,n]
b   []
c   [x,a]
....

我想像这样合并单元格

merged
a,c,v,b,n
b
c,x,a

我尝试了这个pd.DataFrame({'merged' : fdf.groupby(['id'])['rel'].apply(",".join)}).reset_index() 但我收到此错误预期的 str 实例,找到列表 有什么想法吗?

最佳答案

In [11]:
ind = pd.Series(df.index)
ind
Out[11]:
0    a
1    b
2    c
dtype: object

In [20]:
list_string = df.rl.map(lambda x : ','.join(x))
list_string
Out[20]:
a    c,v,b,n
b           
c        x,a
Name: rl, dtype: object

In [22]:
final = ind.str.cat(list_string, sep = ',')
final
Out[22]:
0    a,c,v,b,n
1           b,
2        c,x,a
dtype: object

# to remove the comma at the end of string you can simply do the following
# final.str.replace(',$' , '')
# 0    a,c,v,b,n
# 1            b
# 2        c,x,a
# dtype: object

In [24]:
pd.DataFrame(final , columns=['merged'])
Out[24]:
    merged
0   a,c,v,b,n
1   b,
2   c,x,a

关于python - 合并包含列表的数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736220/

相关文章:

python - 使用 matplotlib 创建热图

python - 接收到str/int错误,无法理解原因

python - Pandas 使用 dfA 列合并 == dfB 索引

python - 在 Pandas 中用 NaN 替换空白值(空格)

python - 格式化与python真正不一致的日期

python - 数据标准化

r - 制作矩阵数字和名称顺序

python - Dataframe-按行的最大值归一化每一行

复制列名并拼接

python - WxPython,在简单的 GUI 中使用缓冲 DC 和面板刷新(转速计数器和条形图)