gpt4 book ai didi

python - 使用相似数据合并 2 个 pandas 数据框

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:13 25 4
gpt4 key购买 nike

我找不到合并这两个数据集的优雅解决方案:

假设我有第一个数据集,包含城市的温度

       2016 2017
cityA 23 27
cityB 24 28

另一个有很多信息,但看起来像这样:

    city    year    other
0 cityA 2016 aa
1 cityB 2017 bb
2 cityA 2016 cc
3 cityB 2017 dd

我想要以下结果:

     city  year other  temperatures
0 cityA 2016 aa 23
1 cityB 2017 bb 28
2 cityA 2016 cc 23
3 cityB 2017 dd 24

感谢您的帮助!

编辑:真实且更复杂的数据帧:

带温度的数据框 1 enter image description here

数据帧 2 和其他数据: enter image description here

答案执行结果:

enter image description here

最佳答案

使用stackreset_index reshape 然后merge ,我认为左连接:

df11 = df1.stack().reset_index()
df11.columns = ['city','year','temperatures']
#if years are strings convert to integers
df11['year'] = df11['year'].astype(int)

df = df2.merge(df11, on=['city','year'], how='left')
print (df)
city year other temperatures
0 cityA 2016 aa 23
1 cityB 2017 bb 28
2 cityA 2016 cc 23
3 cityB 2017 dd 28

关于python - 使用相似数据合并 2 个 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51096736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com