python - 在 python/pandas 中连接文本和数字

标签 python pandas numpy

我有一个数据框如下

+---+---+---+
| A | B | C |
+---+---+---+
| 1 | 0 | 0 |
+---+---+---+
| 0 | 0 | 1 |
+---+---+---+
| 2 | 1 | 1 |
+---+---+---+
| 3 | 1 | 2 |
+---+---+---+
| 4 | 2 | 3 |
+---+---+---+

df = pd.DataFrame({
    'A':[1,0,2,3,4],
    'B':[0,0,1,1,2],
    'C':[0,1,1,2,3]
})

我的目标是将每个元素与其相应的列名称连接并生成一个系列。

我尝试了以下

df.dot(df.columns +', ').str[:-2]

我得到的是

+---------------------------+
| A                         |
+---------------------------+
| C                         |
+---------------------------+
| A, A, B, C                |
+---------------------------+
| A, A, A, B, C, C          |
+---------------------------+
| A, A, A, A, B, B, C, C, C |
+---------------------------+

但是,我想要的是

+------------+
| A          |
+------------+
| C          |
+------------+
| 2A, B, C   |
+------------+
| 3A, B, 2C  |
+------------+
| 4A, 2B, 3C |
+------------+

我应该如何更改代码才能实现此目的?

最佳答案

关于 lambda 函数的一个想法:

f = lambda x: ', '.join(f'{v}{k}' if v != 1 else k for k, v in x[x > 0].items())
df = df.apply(f, axis=1)
print (df)
0             A
1             C
2      2A, B, C
3     3A, B, 2C
4    4A, 2B, 3C
dtype: object

另一个融合的想法,删除 0 行,将数字与列名连接起来,最后在 groupby 中连接:

df = df.melt(ignore_index=False)
df = df[df['value'].ne(0)]
df['variable'] = df['value'].mask(df['value'].eq(1), '').astype(str) + df['variable']

df = df.groupby(level=0)['variable'].agg(', '.join)
print (df)
0             A
1             C
2      2A, B, C
3     3A, B, 2C
4    4A, 2B, 3C
Name: variable, dtype: object

     

关于python - 在 python/pandas 中连接文本和数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66328090/

相关文章:

python-3.x - 将列表列表转换为字符串 pandas 数据框

python - 如何在图表中运行 elif 函数?

python - 我如何获得点积但没有求和

python - managed=False 时如何运行 django 测试

python - 类型错误 : 'data' is an invalid keyword argument for this function

python - 如何从 views.py 测试选中的单选按钮?

python - 如何 reshape 这个 numpy 数组以排除 "extra dimension"?

python - 图像下载输出不会将所有图像保存在特定文件夹中

python - 用 bool 数组掩盖系列

python - 具有 2 个组件的 pca 输出 1 个特征