简体   繁体   English

如何将 pandas dataframe 转换为具有 Column==value 列的表?

[英]How to convert pandas dataframe to a table with Column==value columns?

Since I don't know the name of the concept I am looking for, googling it has made but no success...由于我不知道我正在寻找的概念的名称,因此在谷歌上搜索它已经成功但没有成功......

I need to convert something like:我需要转换类似的东西:

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

to something like:类似于:

   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

I am using python 3.8 and pandas 1.1.3 Many thanks in advance...我正在使用 python 3.8 和 pandas 1.1.3 非常感谢提前...

Use get_dummies with convert all values to strings and set prefix_sep parameter:使用get_dummies将所有值转换为字符串并设置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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM