【问题标题】:pandas: populate an empty column in a dataframe with values from multiple dataframes based on similar values in one columnpandas:根据一列中的相似值,使用来自多个数据帧的值填充数据帧中的空列
【发布时间】:2020-07-10 22:18:13
【问题描述】:

我有一个大数据框,它有两列但有很多行,所以这只是一个例子:

df1 = {"text":["see you in five minutes.", "she is my friend.", "she goes to school in five minutes.","he is my friend.","that is right.","sky is blue.","sky is yellow."],
       "goal":[" "," "," "," "," "," "," "]}

我还有其他三个不同大小的数据框,但它们都有来自 df1 中文本列的一些行:

 df2= {"text":["see you in five minutes.", "he is my friend."],
       "second":["num","friend"]}

 df3 = {"text":["she goes to school in five minutes.","she is my friend.","that is right."],
       "third":["num","friend","correct"]}

 df4 = {"text":["sky is blue.","sky is yellow."],
       "fourth":["color","color"]}

我想要做的是将“第二”、“第三”和“第四”列合并到 df1,以便它们填充 df1 中的空列“目标”,

 desired output:
 df1 = {"text":["see you in five minutes.", "she is my friend.", "she goes to school in five minutes.","he is my friend.","that is right.","sky is blue.","sky is yellow."],
       "goal":["num","friend","num","friend","correct","color","color"]}

我为每个数据框尝试了多次左合并,但输出将出现在不同的列中。有没有办法一次完成并将它们添加到目标列?

谢谢

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    通过使用pd.concat 连接数据帧df2df3df4 创建映射系列m,然后使用此映射系列和Series.map 来映射df1 中的文本列:

    m = pd.concat([df.set_index('text').iloc[:, 0] for df in (df2, df3, df4)])
    df1['goal'] = df1['text'].map(m)
    

    结果:

    # print(df1)
                                      text     goal
    0             see you in five minutes.      num
    1                    she is my friend.   friend
    2  she goes to school in five minutes.      num 
    3                     he is my friend.   friend
    4                       that is right.  correct
    5                         sky is blue.    color
    6                       sky is yellow.    color
    

    【讨论】:

      猜你喜欢
      • 2021-07-13
      • 2019-07-10
      • 1970-01-01
      • 2022-07-06
      • 2021-01-11
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多