熊猫有条件地将数据框添加到另一个数据框

时间:2018-12-12 02:24:58

标签: python python-3.x pandas

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"]})
  • 如何从前两个数据框bf_1和bf_2创建df_final数据框?

  • 如何编码这种情况: 如果输入“ Horse1”,则如上所述将其删除,否则将其添加到底部。

1 个答案:

答案 0 :(得分:0)

使用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