gpt4 book ai didi

python - Pandas 有条件地将数据框添加到另一个数据框

转载 作者:行者123 更新时间:2023-11-28 19:00:00 25 4
gpt4 key购买 nike

from pandas import DataFrame
import pandas as pd

df_1 = pd.DataFrame(
{
'Horses':["Horse1","Horse2","Horse3"],
'Age':[2,5,3],
'Price':["$100,000","$80,000","$60,000"],
'Weight':["180g","140kg","240kg"]})

df_2 = pd.DataFrame(
{
'Horses':["Horse4","Horse1","Horse5"],
'Age':[4,3,2],
'Price':["$75,000","$35,000","$120,000"],
'Weight':["210kg","110kg","197kg"]})



df_final = pd.DataFrame(
{
'Horses':["Horse1","Horse2","Horse3","Horse4","Horse5"],
'Age':[2,5,3,4,2],
'Price':["$100,000","$80,000","$60,000","$75,000","$120,000"],
'Weight':["180g","140kg","240kg","210kg","197kg"]})
  • 如何从前两个 DataFrame bf_1 和 bf_2 创建 df_final DataFrame?

  • 如何编写此条件代码:如果输入“Horse1”,它会像上面一样被删除,否则它会被添加到底部。

最佳答案

使用combine_first

df_1.set_index('Horses',inplace=True)
df_1=df_1.combine_first(df_2.set_index('Horses')).reset_index()
df_1
Horses Age Price Weight
0 Horse1 2.0 $100,000 180g
1 Horse2 5.0 $80,000 140kg
2 Horse3 3.0 $60,000 240kg
3 Horse4 4.0 $75,000 210kg
4 Horse5 2.0 $120,000 197kg

关于python - Pandas 有条件地将数据框添加到另一个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735200/

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