我正在嘗試使用 Pandas 過濾 excel 電子表格并將過濾后的資料保存到新作業表中。目前我有這個按預期作業
import pandas as pd
df = pd.read_excel('sample.xlsx', sheet_name=0) #reads the first sheet of your excel file
df = df[(df['CodedCorporation'] == 'lucy')] #Filtering dataframe
df.to_excel('sample.xlsx', sheet_name='new data') #Saving to a new sheet called Filtered Data
問題是此代碼在標題為“CodedCorporation”的列中查找單詞“Lucy”的完全匹配項。我需要的是能夠根據部分匹配而不是完全匹配進行過濾。
所以我試過這個
import pandas as pd
df = pd.read_excel('sample.xlsx', sheet_name=0) #reads the first sheet of your excel file
df = df[('lucy' in df['CodedCorporation'])] #Filtering dataframe
df.to_excel('sample.xlsx', sheet_name='new data') #Saving to a new sheet called Filtered Data
但這會引發錯誤。
有人可以幫助解釋如何在列中查找部分匹配而不是完全匹配嗎?有點像當您在 excel 中作業并在過濾器中鍵入一個單詞時,excel 會顯示包含該單詞的所有內容。
uj5u.com熱心網友回復:
您可以使用帶有 lambda的apply方法來運行逐行邏輯。
取而代之的是:
df = df[('lucy' in df['CodedCorporation'])] #Filtering dataframe
你可以創建一個像“lucy_ind”這樣的標志:
df["lucy_ind"] = df.apply(lambda x: True if 'lucy' in x['CodedCorporation'] else False, axis=1)
...然后對其進行過濾(僅包括露西在 CodedCorporation 中的行)...您只需執行以下操作:
df = df[df["lucy_ind"]]
uj5u.com熱心網友回復:
您可以使用此處記錄的屬性中的contains()函式str
import pandas as pd
df = pd.DataFrame(
[
"has lucy",
"also has lucy in it",
"this line doesn't"
],
columns=["CodedCoporation"]
)
filtered_df = df[df.CodedCoporation.str.contains('lucy')]
filtered_df.to_markdown()
| 編碼公司 | |
|---|---|
| 0 | 有露西 |
| 1 | 里面也有lucy |
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/367240.html
