我有一個名為df 的資料框 ,它有兩列 id1 和 id2
我需要根據其他一些名為meta_df 的df 過濾值
meta_df 有三列 id,name,text
df
| 編號1 | 編號2 |
|---|---|
| 12 | 34 |
| 99 | 42 |
元資料
| ID | 姓名 | 文本 |
|---|---|---|
| 12 | aa | 低端 |
| 42 | bb | 上端 |
| 99 | 抄送 | 上限 |
| 34 | 日 | 上流社會 |
我需要文本字串中具有較低和較高的文本值。例如 12 和 34 我正在嘗試下面的代碼并堅持獲取文本 clumn
for row in df.itertuples():
print(row.Index, row.id1, row.id2)
print(meta_df[id['id']== row.id1])
print(meta_df[id['id']== row.id2])
預期產出
| 編號2 | 編號2 | 旗幟 |
|---|---|---|
| 12 | 34 | 是的 |
| 99 | 42 | 不 |
uj5u.com熱心網友回復:
融化df并合并到metadf,在獲得最終值之前進行一些重塑:
# keep the index with ignore_index
# it will be used when reshaping back to original form
reshaped = (df.melt(value_name = 'id', ignore_index = False)
.assign(ind=lambda df: df.index)
.merge(metadf, on='id', how = 'left')
.assign(text = lambda df: df.text.str.contains('lower'))
.drop(columns='name')
.pivot('ind', 'variable')
.rename_axis(columns=[None, None], index=None)
)
# if the row contains both lower(1) and upper(0)
# it will sum to 1, else 0, or 2(unlikely with the sample data shared)
flag = reshaped.loc(axis=1)['text'].sum(1)
reshaped.loc(axis=1)['id'].assign(flag = flag.map({1:'yes', 0:'no'}))
id1 id2 flag
0 12 34 yes
1 99 42 no
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/311116.html
上一篇:AttributeError:模塊“keras.backend.tensorflow_backend”沒有屬性“set_image_dim_ordering”
