Conditionally concat a dataframe in python using pandas -
i have data frame
df
b 0 test1 1 1 test2 4 2 test3 1 3 test4 2
df1
c 0 test3 1 test5
i want conditionally merge them new dataframe
df2
b 0 test1 1 1 test2 4 2 test3 0 3 test4 2 4 test5 0
a new data frame if value in column equal column c, while merging update column b value default of 0 , if there there isn't value exists in column equal value in column c add data frame shown above default value of 0.
here simple approach. take element second dataframe in col c
not in col a
on first dataframe - , concatenate setting missing values 0
. use small hack in groupby
in case there several same values in col a
, select 1 0
:
pd.concat([df,df1.rename(columns={'c':'a'})]).fillna(0).groupby('a', as_index=false).last() b 0 test1 1 1 test2 4 2 test3 0 3 test4 2 4 test5 0
Comments
Post a Comment