问题
I have two dataframes:
df_1:
Letters Boolean
a Nan
b Nan
c Nan
df_2:
a b d
2.7 1.2 3.6
1 2 3
How do I check if df_1['letters'] is present in df_2.keys(). If it is present, I want boolean to take the value 'x': Something like:
Letters Boolean
a x
b x
c Nan
I tried using this code:
for x in df_1['letters']:
if x in df_2.keys():
df_1['Boolean']='x'
回答1:
Use numpy.where with isin:
df1['Boolean'] = np.where(df1['Letters'].isin(df2.columns), 'x', np.nan)
回答2:
You need :
df1['Boolean']=df1.Letters.isin(df2.columns).map({True:'x',False:np.nan})
print(df1)
Letters Boolean
0 a x
1 b x
2 c NaN
来源:https://stackoverflow.com/questions/54551692/how-to-check-if-a-value-in-one-dataframe-is-present-in-keys-in-the-other-datafra