代码之家  ›  专栏  ›  技术社区  ›  XYZ

如何将每行的每个字转换为数据帧的数值

  •  1
  • XYZ  · 技术社区  · 2 年前

    这个数据框是给我的。

    enter image description here

    我希望使用字典输出如下

    **Given the following dictionary:-** 
    d = {'I': 30,'am': 45,'good': 90,'boy': 50,'We':100,'are':70,'going':110}
    

    enter image description here

    如何使用python实现这一点。。

    dataframe['new'] = data['documents'].apply(lambda x: dictionary[x]) 
    

    请帮帮我。提前谢谢。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Corralien    2 年前

    你可以用 explode 要获取单词,然后将其映射到dict并重塑数据帧,请执行以下操作:

    MAPPING = {'I': 30,'am': 45,'good': 90,'boy': 50,'We':100,'are':70,'going':110}
    
    df['documents'] = (df['documents'].str.split().explode().map(MAPPING).astype(str)
                                      .groupby(level=0).agg(list).str.join(' '))
    print(df)
    
    # Output
       id    documents
    0   0  30 45 90 50
    1   1   100 70 110
    2   2    30 45 110