簡體   English   中英

如何從熊貓數據框中過濾掉值?

[英]How to filter out values from pandas dataframe?

我有兩個數據框。 我需要從主數據框中過濾一些值。 我需要一些幫助來做到這一點。 請你幫助我好嗎?

解釋:

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、filter_value 和列。 所以我必須像這樣創建匹配語句 -

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

希望這會奏效-

## 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']]

首先,我從數據框中取了兩列 - 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM