Pandas:在字符串列上合并数据帧

2024-05-23 22:36:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,目前正在从事一个项目,需要合并两个数据帧。其中一个数据框称为癌症发病率(cancer_df),是按县、年、性别、性别等划分的癌症发病率。另一个数据框称为hspa_df,是按县和年划分的健康评分(仅供参考,这是加利福尼亚州唯一的县)。我想结合我关于县和年的两个数据框架Here is the cancer dataframe before the mergeHere is the hspa dataframe before the merge

然后我导入了数据并尝试了以下合并:

merged_df= pd.merge(cancer_df, hspa_df, on="County" , how="outer")

但是,这似乎是附加数据,而不是合并数据。它将我的hspa_df添加到末尾,并填充它们作为NaNs共享的变量的顶部。为什么会这样?我已成功地将此合并用于其他数据帧,但我将它们合并到数字列上,而不是字符串上。 Here is the merged dataframes headHere is the merged dataframes tail


Tags: the数据dataframedfhereismergemerged
1条回答
网友
1楼 · 发布于 2024-05-23 22:36:02

I would like to combine my two dataframe on county and year

merged_df = pd.merge(cancer_df, hspa_df, on=['County', 'Year'] )

是否要进行内部、左侧、右侧等连接取决于您的用例,但请注意如何指定两列

It fills the top of the variable they share in common as NaNs

这就是外部联接所做的,它使用了填充符

相关问题 更多 >