根据值将 df1 列与 df2 列交换

发布于 2025-01-13 07:29:58 字数 935 浏览 1 评论 0原文

目标:基于 'df_state.abbr` 将 df_hsa.stateabbr 替换为 df_state.state

是否有这样的函数,我在其中提到源、目标和基于数据框的列?

我需要以类似的方式订购两个 DataFrame 吗?

df_hsa

   hsa stateabbr    county
0  259        AL    Butler
1  177        AL   Calhoun
2  177        AL  Cleburne
3  172        AL  Chambers
4  172        AL  Randolph

df_state

  abbr       state
0   AL     Alabama
1   AK      Alaska
2   AZ     Arizona
3   AR    Arkansas
4   CA  California

所需输出: df_hsastate 列而不是 stateabbr

   hsa     state    county
0  259   Alabama    Butler
1  177   Alabama   Calhoun
2  177   Alabama  Cleburne
3  172   Alabama  Chambers
4  172   Alabama  Randolph

Goal: swap out df_hsa.stateabbr with df_state.state, based on 'df_state.abbr`.

Is there such a function, where I mention source, destination, and based-on dataframe columns?

Do I need to order both DataFrames similarly?

df_hsa:

   hsa stateabbr    county
0  259        AL    Butler
1  177        AL   Calhoun
2  177        AL  Cleburne
3  172        AL  Chambers
4  172        AL  Randolph

df_state:

  abbr       state
0   AL     Alabama
1   AK      Alaska
2   AZ     Arizona
3   AR    Arkansas
4   CA  California

Desired Output:
df_hsa with state column instead of stateabbr.

   hsa     state    county
0  259   Alabama    Butler
1  177   Alabama   Calhoun
2  177   Alabama  Cleburne
3  172   Alabama  Chambers
4  172   Alabama  Randolph

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

铃予 2025-01-20 07:29:58

您可以在将索引设置为“stateabbr”

df_hsa.set_index("stateabbr").join(df_state.set_index("abbr"))

输出后简单地加入:

    hsa county  state
AL  259 Butler  Alabama
AL  177 Calhoun Alabama
AL  177 Cleburne    Alabama
AL  172 Chambers    Alabama
AL  172 Randolph    Alabama

如果您还想要原始索引,可以在行末尾添加 .set_index(df_hsa.index)

you can simply join after setting the index to be "stateabbr"

df_hsa.set_index("stateabbr").join(df_state.set_index("abbr"))

output:

    hsa county  state
AL  259 Butler  Alabama
AL  177 Calhoun Alabama
AL  177 Cleburne    Alabama
AL  172 Chambers    Alabama
AL  172 Randolph    Alabama

if you also want the original index your can add .set_index(df_hsa.index) at the end of the line

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文