根据键填充NaN值

时间:2019-12-19 21:22:11

标签: python-3.x pandas

我正在尝试根据两个数据框中都存在的键在另一个数据框中填充空值。

Case when {item.custitem54} = 'Yes' 
          and {shipdate} between date '2020-05-25' and date '2020-12-25' then {quantity} 
     when {item.custitem54} is null then {quantity} 
     else null 
end
df

parcel     ID
1234       NaN
4586       lmnop
5960       wywy

由于df和df1中的包裹号相同,因此我只想基于df1填充ID列中的空值。

3 个答案:

答案 0 :(得分:1)

您可以使用map,它允许您使用字典来映射值。

na_dict = dict(zip(df1.Parcel,df1.ID))

df.ID.fillna(df.ID.map(na_dict))

答案 1 :(得分:1)

您可以使用combine_first

df.combine_first(df1)

输出:

   parcel     ID
0    1234   abcd
1    4586  lmnop
2    5960   wywy

答案 2 :(得分:1)

我认为combine_first()是个好方法,但是您需要先设置索引-在这种情况下,列parcel在这两种情况中都很常见:

import numpy as np
import pandas as pd

df = pd.DataFrame({
    'parcel': [1234, 4586, 5960, 9999],
    'ID': [np.nan, 'lmnop', 'wywy', np.nan]
    })

df1 = pd.DataFrame({
    'parcel': [1234, 4586, 9999, 8888],
    'ID': ['abcd', 'lmnop', 'xxx', 'nonexistent']
    })

df_out = df.set_index('parcel').combine_first( df1.set_index('parcel') )
df_out = df_out[df_out.index.isin(df.parcel)].reset_index()
print(df_out)

打印:

   parcel     ID
0    1234   abcd
1    4586  lmnop
2    5960   wywy
3    9999    xxx
相关问题