如何将dataframe转换为列==值列的表?

2024-04-25 00:31:22 发布

您现在位置:Python中文网/ 问答频道 /正文

由于我不知道我正在寻找的概念的名称,谷歌搜索它取得了成功,但没有成功

我需要转换如下内容:

   a   b        c   d
   1   2    'Hey'   4
   2   2  'Hello'   4
   1   2  'World'   3

例如:

   a==1  a==2  b==2  c=='Hey'  c=='Hello'  c=='World'   d==3    d==4
      1     0     1         1           0           0      0       1
      0     1     1         0           1           0      0       1
      1     0     1         0           0           1      1       0

我正在使用python 3.8和pandas 1.1.3 非常感谢


Tags: 名称概念内容hellopandasworldhey
1条回答
网友
1楼 · 发布于 2024-04-25 00:31:22

使用^{}将所有值转换为字符串并设置prefix_sep参数:

df = pd.get_dummies(df.astype(str), prefix_sep='==')
print (df)
   a==1  a==2  b==2  c=='Hello'  c=='Hey'  c=='World'  d==3  d==4
0     1     0     1           0         1           0     0     1
1     0     1     1           1         0           0     0     1
2     1     0     1           0         0           1     1     0

相关问题 更多 >