简体   繁体   English

通过匹配变量将值从一个 pandas dataframe 添加到另一个 dataframe

[英]Adding value from one pandas dataframe to another dataframe by matching a variable

Suppose I have a pandas dataframe df with 2 columns假设我有一个带有 2 列的 pandas dataframe df

           c1            c2
    0      v1            b1
    1      v2            b2
    2      v3            b3
    3      v4            b4
    4      v5            b5

A second dataframe, df2 contains c1, c2 and a few other columns.第二个 dataframe, df2包含 c1、c2 和其他一些列。

   c1 c2 c3  c4
0  "" b5 500 3
1  "" b2 420 7
2  "" b1 380 5
3  "" b2 470 9
4  "" b3 290 2

My goal is to replace the empty values for c1 in df2, with those in df, corresponding to the values in c2, so the first five values for c1 in df2, should be v5,v2,v1,v2 and v3 respectively.我的目标是将 df2 中 c1 的空值替换为 df 中的空值,对应于 c2 中的值,因此 df2 中 c1 的前五个值应分别为 v5、v2、v1、v2 和 v3。 What is the best way to do this?做这个的最好方式是什么?

One easy way you can do is to use the merge of pandas based on similar column.您可以做的一种简单方法是使用基于类似列的 pandas 的合并。

df2.drop('c1', axis=1, inplace=True)
main_df = pd.merge(df2, df, on="c2", how="left")
df2['c1'] = main_df['c1']
df2.columns = ['c1','c2','c3','c4']

Something like this might be what you're looking for:像这样的东西可能是你正在寻找的东西:

import pandas as pd
import numpy as np
# remove the c1 column from df2
df2.drop("c1", axis=1, inplace=True)
# merge the 2 dataframes and get the c1 values corresponding to c2
newdf = df.merge(df2, on="c2")

If you actually have missing values in the column (ie NAs and some rows where values are present, the solution will be different)如果您在列中确实有缺失值(即 NA 和一些存在值的行,则解决方案会有所不同)

暂无
暂无

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

相关问题 如果来自一个 dataframe 的值存在于另一个 dataframe 中,则 Pandas 赋值 - Pandas assign value if value from one dataframe exists in another dataframe Python Pandas检查值是否从一个DataFrame到另一个DataFrame - Python Pandas checking for a value if it exists from one DataFrame to another DataFrame Python / Pandas-用另一个数据框中的值替换一个数据框中的元素 - Python/Pandas - Replacing an element in one dataframe with a value from another dataframe 熊猫-用另一个数据框的值填充一个数据框的每一行 - Pandas - Filling each rows of one Dataframe with value from another Dataframe 从另一个数据帧向 Pandas 数据帧添加行 - Adding rows to a Pandas dataframe from another dataframe 如果行在Pandas数据帧中具有匹配的子字符串,则将值从一行添加到另一行 - Add value from one row to another row if rows have matching substrings in Pandas dataframe Pandas数据帧通过匹配另一个数据帧中的值来划分值 - Pandas dataframe divide value by matching value in another dataframe Python/Pandas:在一个 dataframe 中搜索日期,并在另一个 dataframe 的列中返回具有匹配日期的值 - Python/Pandas: Search for date in one dataframe and return value in column of another dataframe with matching date 将一个数据帧中的列添加到另一个 python pandas - Adding column(s) from one dataframe to another python pandas 熊猫:在一个数据框中创建新列,并根据与另一个数据框中的匹配键进行匹配 - Pandas: create new column in one dataframe with values based on matching key from another dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM