我有一個熊貓資料框,其中有“生物位置”列,我想對其進行過濾,以便我只有串列中包含城市名稱的位置。我已經制作了以下代碼,除了我有問題之外。
例如,如果位置是“法國巴黎”并且我的串列中有巴黎,那么它將回傳結果。但是,如果我有“法國巴黎”,它不會回傳“巴黎”。你有解決方案嗎?也許使用正則運算式?非常感謝你!!!
df = pd.read_csv(path_to_file, encoding='utf-8', sep=',')
cities = [Paris, Bruxelles, Madrid]
values = df[df['Bio Location'].isin(citiesfr)]
values.to_csv(r'results.csv', index = False)
uj5u.com熱心網友回復:
你想要的是.str.contains():
1.我用來測驗的DF:
df = {
'col1':['Paris France','France Paris Test','France Paris','Madrid Spain','Spain Madrid Test','Spain Madrid'] #so tested with 1x at start, 1x in the middle and 1x at the end of a str
}
df = pd.DataFrame(df)
df
結果:
| 指數 | col1 |
|---|---|
| 0 | 法國巴黎 |
| 1 | 法國巴黎測驗 |
| 2 | 法國 巴黎 |
| 3 | 西班牙馬德里 |
| 4 | 西班牙馬德里測驗 |
| 5 | 西班牙馬德里 |
2.然后應用下面的代碼:
更新了以下評論 #so 在開始時使用 1x 進行測驗,在中間使用 1x,在 str 結束時使用 1x
reg = ('Paris|Madrid')
df = df[df.col1.str.contains(reg)]
df
結果:
| 指數 | col1 |
|---|---|
| 0 | 法國巴黎 |
| 1 | 法國巴黎測驗 |
| 2 | 法國 巴黎 |
| 3 | 西班牙馬德里 |
| 4 | 西班牙馬德里測驗 |
| 5 | 西班牙馬德里 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484950.html
上一篇:通過一列串列逐行迭代并在新的熊貓資料框中將匹配項轉換為X
下一篇:重現沒有資料的圖形
