我的示例資料幀是:
| 檔案 | Voucher_stand |
|---|---|
| 90.txt | SCA |
| 90.txt | 渣打銀行 |
| 60.txt | 世界足聯 |
| 60.txt | 世界貿易組織 |
| 90.txt | SCA |
| 50.txt | SCA |
| 80.txt | SCA |
| 100.txt | SCA |
我想定義一個字典,我可以根據它選擇一些列,但是每個檔案在 Voucher_stand 列中都有自己的代碼,如何根據 Voucher_stand 和檔案按字典過濾此 DataFrame 而不是每次都使用串列?
例如,在字典中定義 Voucher_Stand 和 files,然后根據此字典過濾我的 DataFrame:
code = {'90.txt':['SCA', 'SCB'], '60.txt':['WFA', 'WFO']}
uj5u.com熱心網友回復:
嘗試這個:
pd.DataFrame(df.set_index('file').groupby('file')['Voucher_stand'].apply(list)).T.reset_index(drop=True)
您可以dict通過呼叫.to_dict()以下方式獲取它:
pd.DataFrame(df.set_index('file').groupby('file')['Voucher_stand'].apply(list)).T.reset_index(drop=True).to_dict()
uj5u.com熱心網友回復:
您可以使用items鍵和代碼isin串列的相等比較來迭代字典并過濾所需的行Voucher_stand。然后,獲取行的索引作為串列并將其保存到變數中。用于iloc僅選擇符合條件的行。
import pandas as pd
df = pd.read_csv('sample.csv', sep='\s ')
print(df)
CODE = {'90.txt':['SCA', 'SCB'], '60.txt':['WFA', 'WFO']}
filtered_rows = []
for k,v in CODE.items():
filtered_rows = df[(df['file'] == k) & df['Voucher_stand'].isin(v)].index.to_list()
result = df.iloc[filtered_rows]
print(result)
結果輸出
file Voucher_stand
0 90.txt SCA
1 90.txt SCB
4 90.txt SCA
2 60.txt WFA
3 60.txt WFO
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358201.html
上一篇:根據當前值更改字典中的多個值
