我有两个数据框。我需要从主数据框中过滤一些值。我需要一些帮助。你能帮我吗?
说明:
df_main:
kol_id|jnj_id|kol_full_nm|foc_area_id|thrc_cd|thrc_nm|dis_area|dis_area_nm|expert_score|pub_scor|rx_scor|refrl_scor|clincl_rsrchr_scor|is_kol
101152|7124166|Constance Ann Benson|1|VIR|VIR|HIV|HIV|45.17|68.5|0|1.69|88|Y
251489|7822721|Mariam S Aziz|1|VIR|VIR|HIV|HIV|44.33|39.5|33|34.26|76|Y
100856|7356682|William Rodney Short|1|VIR|VIR|HIV|HIV|49.49|44|57.5|50.39|48|Y
251460|7933108|Laura A Guay|1|VIR|VIR|HIV|HIV|34.8|63|0|0|48|N
df2:
filter filter_value columns user_id password api_name
kol_id 101152 kol_id vmani4 abede1234 KOL
thrc_nm VIR jnj_id vmani4 abede1234 KOL
jnj_id 7124166 kol_full_nm vmani4 abede1234 KOL
thrc_cd vmani4 abede1234 KOL
我必须借助df2过滤掉df_main中的值。 在df2中,它具有3列-过滤器,filter_value和列。所以我必须以这种方式创建match语句-
if(kol_id == '101152' and thrc_nm == 'VIR' and jnj_id == '7124166')
Then extract only those column records from df_main which is present in df2['columns']
但是问题是filter和filter_value列记录不确定,这意味着它正在由api_name更改。因此,我需要编写适用于所有api的代码。 如果您需要更多信息,请告诉我。
表示最终结果
df_result:
kol_id|jnj_id|kol_full_nm|thrc_cd|
101152|7124166|Constance Ann Benson|VIR
答案 0 :(得分:0)
希望这会起作用-
## For this case you'll have to add these 2 lines to avoid comparing str to int
## and to avoid nans in last row of df2
df_final = df_main.copy().astype(str)
df2 = df2[:3].astype(str)
for i, row in df2.iterrows():
df_final = df_final[df_final[row['filter']]==row['filter_value']]
答案 1 :(得分:0)
首先,我从数据框中提取了两列-filter和filter_value。创建了一个临时数据框。然后我转置了临时数据帧,并重置了索引并删除了标头。
filter_u = df['filter'].unique()
filter_u = [str(i) for i in filter_u]
filter_u = ' '.join(filter_u).split()
column_u = df['columns'].unique()
column_u = [str(i) for i in column_u]
column_u = ' '.join(column_u).split()
print(filter_u)
print(column_u)
df_t1 = df[['filter', 'filter_value']]
df_t1 = df_t1.transpose().reset_index(drop=True)
df_t1 = df_t1.astype(str)
df_t1.columns = df_t1.iloc[0]
df_t1 = df_t1.reindex(df_t1.index.drop(0)).reset_index(drop=True)
df_t1.columns.name = None
以上代码的输出:
kol_id thrc_nm jnj_id
0 101152 VIR 7124166.0
然后,我将主文件作为数据框读取,并与上述数据框合并,最后得到想要的结果。
df_main = pd.read_csv("/medaff/Scripts/python/vinooth/kol_scores.txt", delimiter = '|')
df_main = df_main.astype(str)
print(df_main.head())
df_3=pd.merge(df_main,df_t1,on=filter_u,how='inner')
df_3 = df_3[df_3.columns & column_u]
print(df_3)
df_3.to_json('/medaff/Scripts/python/vinooth/output/out.json', orient='records')
通过这种方式,我得到了最终输出:
kol_id jnj_id kol_full_nm thrc_cd
0 101152 7124166.0 Constance Ann Benson VIR