简体   繁体   English

如果 df2 中不存在列,如何将列从 df1 添加到 df2,否则什么也不做

[英]How to add a column from df1 to df2 if it not present in df2, else do nothing

I have 2 data frame from a basic web scrape using Pandas (below).我有 2 个来自基本 web 刮擦的数据框,使用 Pandas(下图)。 The second table has less columns than the first, and I need to concat the dataframes.第二个表的列比第一个少,我需要连接数据框。 I have been manually inserting columns for a while but seeing as they change frequently I would like to have a function that can assess the columns in df2, check whether they are all in df2, and if not, add the column, with the data from df2.我已经手动插入列有一段时间了,但是看到它们经常变化,我想要一个 function 可以评估 df2 中的列,检查它们是否都在 df2 中,如果没有,添加列,数据来自df2。

import pandas as pd 

link = 'https://en.wikipedia.org/wiki/Opinion_polling_for_the_next_French_presidential_election'
df = pd.read_html(link,header=0)

df1 = df[1]
df1 = df1.drop([0])
df1 = df1.drop('Abs.',axis=1)

df2 = df[2]
df2 = df2.drop([0])
df2 = df2.drop(['Abs.'],axis=1)

Many thanks,非常感谢,

@divingTobi's answer: @divingTobi 的回答:

pd.concat([df1, df2]) does the trick. pd.concat([df1, df2])可以解决问题。

暂无
暂无

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

相关问题 熊猫:如何正确执行df2中的行= df1中的列? - Pandas: how to do row in df2 = column in df1 properly? pandas 如何从 df2 获取 df1 的值,而 df1 和 df2 的值在列上重叠 - pandas how to get values from df2 for df1 while df1 and df2 have values overlapped on column(s) Python - 检查df2列中是否存在df1列中的值 - Python - Check if a value in a df1 column is present in df2 column 如何向 dataframe (df1) 添加一个新列,这是另一个 dataframe (df2) 中 df1 的多个查找值的总和 - How can I add a new column to a dataframe (df1) that is the sum of multiple lookup values from df1 in another dataframe (df2) 从 DF2 替换 DF1 中的值 - Replace values in DF1 from DF2 如何在熊猫中进行“(df1&not df2)”数据框合并? - How to do "(df1 & not df2)" dataframe merge in pandas? 如何获取 df1 中存在但 df2 中不存在的行,反之亦然,同时忽略列“值” - How to get rows which are present in df1 but not in df2 and vice versa while ignoring the column 'value' 如何将两个不同的数据框 df1 df2 与特定列(列 w)进行比较,并从 df2 更新 df1 中匹配的行列 AD - how to compare two different data frames df1 df2 with specific column ( column w) and update the matched rows column AD in df1 from df2 如何通过匹配 df1 中与 df2 索引和列名匹配的列值来用 df1 中的数据填充 df2 - How to fill df2 with data from df1 by matching column values from df1 which match df2 index and column names 当 df2 中的日期早于 df1 中的日期时,如何检查 df1 中的 id 是否存在于 df2 中,并使用 pandas 相应地添加新列 - how to check whether the id in df1 existed in df2 when date in df2 is older than date in df1 and add new column accordingly using pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM