pandas 从不同于零的行中获取列的名称python

uyto3xhc  于 2023-03-28  发布在  Python
关注(0)|答案(3)|浏览(135)

我有这个 Dataframe :

df0 = pd.DataFrame({'points': [0, 0, -3, 16, 0, 5, -3, 14],
                    'assists': [0, 0, 2, 0, 1, -7, 0, 6],
                    'numbers': [0, 0, 1, 6, 10, 5, 8, 7]})

我想要的数据集看起来像这样:

points assists numbers colX
0      0       0        0
0      0       0        0
-3     2       1       'points-assists-numbers'
16     0       6       'points-numbers'
0      1       10      'assists-numbers'
5      7       5       'points-assists-numbers'
-3     0       8       'points-numbers'
14     8       7       'points-assists-numbers'

一个函数,它从具有不同于零的值的列名创建字符串。
有人帮忙吗?

u3r8eeie

u3r8eeie1#

这种操作非常适合lambda表达式。
类似这样的方法应该可以奏效:
df0['colX'] = df0.apply(lambda x: '-'.join(c for c in df0.columns if x[c] != 0), axis=1).replace('', 0)

  • 首先它得到一个不为0的列的列表
  • 用“-”连接这些列的名称
  • 之后,用0填充空白名称
ohtdti5x

ohtdti5x2#

您可以尝试使用dot

df0['new'] = df0.ne(0).dot(df0.columns+'_').str[:-1]
df0
Out[9]: 
   points  assists  numbers                     new
0       0        0        0                        
1       0        0        0                        
2      -3        2        1  points_assists_numbers
3      16        0        6          points_numbers
4       0        1       10         assists_numbers
5       5       -7        5  points_assists_numbers
6      -3        0        8          points_numbers
7      14        6        7  points_assists_numbers
5cg8jx4n

5cg8jx4n3#

以下是一些选项:

#keep only the values that are not 0 and stack. reset the index so it can be joined by '-' on the index level.
df0['new'] = df0.where(df0.ne(0)).stack().reset_index(level=1).groupby(level=0)['level_1'].agg('-'.join)

#similar to the solution above, but multiplies the column value to avoid resetting index
df0['new'] = df0.ne(0).mul(df0.columns).where(lambda x: x.ne('')).stack().groupby(level=0).agg('-'.join)

#multiplies the column names by values that are not 0, and adds them together.
df0['new'] = df0.ne(0).dot(df0.columns + '-').str.rstrip('-')

相关问题