【问题标题】:How to fill NAN Value base on another dataframe in Python如何在 Python 中基于另一个数据框填充 NAN 值
【发布时间】:2021-10-27 18:49:06
【问题描述】:

如何将这两个数据框合并为我想要的结果?

df1 = pd.DataFrame({'Animals': ['Dog','Cat','Monkey','Snake','bear','dear'],
                    'Price': ['100','NAN','100','70','NAN','100']})

df2 = pd.DataFrame({'Animals': ['Cat','bear'], 'Price': ['50','200']})

result = pd.merge(df1, df2, how='left', on=['Animals'])

想要的结果:

Animals     Price
Dog         100
Cat         50
Monkey      100
Snake       70
bear        200
dear        100

【问题讨论】:

标签: python python-3.x pandas


【解决方案1】:

试试:

df1 = pd.DataFrame(data={'Animals': ['Dog', 'Cat', 'Monkey', 'Snake', 'bear', 'dear'], 'Price': ['100', pd.NA, '100', '70', pd.NA, '100']})
df2 = pd.DataFrame(data={'Animals': ['Cat', 'bear'], 'Price': ['50', '200']})

df1 = df1.set_index('Animals')
df2 = df2.set_index('Animals')

df1['Price'].update(df2['Price'])
df1 = df1.reset_index()
df2 = df2.reset_index()

print(df1)

输出:

  Animals Price
0     Dog   100
1     Cat    50
2  Monkey   100
3   Snake    70
4    bear   200
5    dear   100

【讨论】:

    【解决方案2】:

    如果NAN 将是pd.NAnp.nan,您可以使用combine_first

    import pandas as pd
    
    df1 = pd.DataFrame(data={'Animals': ['Dog', 'Cat', 'Monkey', 'Snake', 'bear', 'dear'], 'Price': ['100', pd.NA, '100', '70', pd.NA, '100']})
    df2 = pd.DataFrame(data={'Animals': ['Cat', 'bear'], 'Price': ['50', '200']})
    
    df1 = df1.set_index(keys='Animals')
    df2 = df2.set_index(keys='Animals')
    result = df2.combine_first(other=df1)
    result = result.reset_index()
    print(result)
    

    【讨论】:

    • 感谢您的回答,看到了它的工作。但有一个排序问题。如何在不排序的情况下合并?
    【解决方案3】:

    这是虚拟数据:

    df1 = pd.DataFrame({'Animals': ['Dog','Cat','Monkey','Snake','bear','dear'],
                        'Price': ['100','NAN','100','70','NAN','100']})
    
    df2 = pd.DataFrame({'Animals': ['Cat','bear'], 'Price': ['50','200']})
    

    首先,您需要将 'NAN' 设为实际的“非数字”值 (np.nan)

    df1['Price'] = pd.to_numeric(df1['Price'], errors='coerce')
    

    然后您可以将 df2 转换为字典以替换值:

    convert_dict = df2.set_index("Animals").to_dict()['Price']
    

    然后,通过替换动物将 nans 替换为字典中的值:

    df1.loc[df1['Price'].isna(),'Price'] = \
        df1.loc[df1['Price'].isna(),'Animals'].replace(convert_dict)
    

    结果:

    |    | Animals   |   Price |
    |---:|:----------|--------:|
    |  0 | Dog       |     100 |
    |  1 | Cat       |      50 |
    |  2 | Monkey    |     100 |
    |  3 | Snake     |      70 |
    |  4 | bear      |     200 |
    |  5 | dear      |     100 |
    

    【讨论】:

      【解决方案4】:

      您可以尝试用零替换 NaN:

      df1 = df1.fillna(0)
      

      【讨论】:

      • 我不想用 0 填充 NA 。只想填充 DF2 值。感谢您的回答
      • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
      猜你喜欢
      • 2019-09-17
      • 2020-10-08
      • 2021-01-17
      • 1970-01-01
      • 2021-01-24
      • 2021-08-11
      • 2020-11-26
      • 2022-01-04
      • 1970-01-01
      相关资源
      最近更新 更多