python - 在 Pandas Dataframe 中使用值为 1 的列创建一个短语列

标签 python pandas dataframe

假设我有这个数据集,我想创建一个短语列,为每列添加一个值为 1 的词...

    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET
0            1           0           0           0           0           1          0
1            0           1           0           0           0           1          0
2            0           0           1           0           0           1          0

如果设置为 1,这是每列短语值的数据框:

          col                  phr
0  SINNOUVEAU     sinistre nouveau
1  PERTETOTAL         perte totale
2  CHANGGARAN  changement garantie
3  SOCLOCATIO     societe location
4  SINISAMEDI               samedi
5  NOMASCONDU        nom different
6   SINIREPET   sinistre repetitif

因此,对于上面的数据框,这是我期望的结果:

    SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  SINIREPET  Phrase
0            1           0           0           0           0           1          0  sinistre nouveau, nom different
1            0           1           0           0           0           1          0  perte totale, nom different
2            0           0           1           0           0           1          0  changement garantie, nom different

最佳答案

假设第一个数据集命名为df,第二个数据集命名为df1: 我们求助df.dot()如下所示:

m=df.rename(columns=df1.set_index('col')['phr'].to_dict())
df['Phrase']=m.dot(m.columns+',').str.rstrip(',')
print(df)

   SINNOUVEAU  PERTETOTAL  CHANGGARAN  SOCLOCATIO  SINISAMEDI  NOMASCONDU  \
0           1           0           0           0           0           1   
1           0           1           0           0           0           1   
2           0           0           1           0           0           1   

   SINIREPET                             Phrase  
0          0     sinistre nouveau,nom different  
1          0         perte totale,nom different  
2          0  changement garantie,nom different 

关于python - 在 Pandas Dataframe 中使用值为 1 的列创建一个短语列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56407292/

相关文章:

python - 减去 Pandas Dataframe 中的条目并存储在新列中

python - 网络爬虫问题 : IndexError: string index out of range

python - 如何构建能够在 Python 中进行热代码交换的 Twisted 服务器?

java - WEKA 库 M5P 返回 Java 异常

r - 将 data.frame 列转换为向量?

python - 基于多种条件在pandas dataframe中进行聚合和转换

python - Django-Celery 数据库访问

python - 通过列连接 Pandas 数据帧并用 'NaN' 填充空白

python - 创建超链接以通过 python 访问多个 Excel 工作表

python - 如何将 UTC 时间戳字符串转换为 pandas 日期时间?