根据熊猫中的2种条件合并2个数据帧

时间:2019-03-19 14:31:53

标签: python pandas dataframe merge nan

如何用第一个df中的值替换NaN值:

<p [attr.contenteditable]="isClicked" [ngClass]="{ 'className': isClicked }">Hello World!</p>
<button (click)="isClicked = !isClicked">Add Class</button>

在第二个df中:

    country   sex    year      cancer
0   Albania  female  2000       32
1   Albania  male    2000       58
2   Antigua  female  2000       2
3   Antigua  male    2000       5
4   Argen    female  2000       591
5   Argen    male    2000       2061

决赛应该像这样:

    country year    sex    cancer
0   Albania 1985    female  NaN
1   Albania 1985    male    NaN
2   Albania 1986    female  NaN
3   Albania 1986    male    NaN
4   Albania 1987    female  25.0
5   Antigua 1992    male    NaN
6   Antigua 1985    female  NaN  

重要的两个条件是国家和性别

1 个答案:

答案 0 :(得分:2)

I am end up using fillna

df2.set_index(['country','sex'],inplace=True)
df2['cancer']=df2['cancer'].fillna(df1.set_index(['country','sex']).cancer)
df2.reset_index(inplace=True)
df2
Out[745]: 
   country     sex  year  cancer
0  Albania  female  1985    32.0
1  Albania    male  1985    58.0
2  Albania  female  1986    32.0
3  Albania    male  1986    58.0
4  Albania  female  1987    25.0
5  Antigua    male  1992     5.0
6  Antigua  female  1985     2.0