這個問題在這里已經有了答案: Pandas 列訪問 w/包含空格的列名 5 個答案 6 小時前關閉。
我想在列中找到第一次出現的子字串。
例如,如果我有以下資料框..
# Create example dataframe
import pandas as pd
data = {
'Tunnel ID':['Tom', 'Dick', 'Harry'],
'State':['Grumbly', 'Very Happy', "Happy"],
'Length':[302, 285, 297]
}
df = pd.DataFrame(data)
..我可以使用以下方法在“狀態”列中找到“快樂”的第一次出現:
# Returns index 1
first_match = df.State.str.contains('Happy').idxmax()
但是,如果我想在“隧道 ID”中找到“ic”的第一個匹配項:
# Returns syntax error because of space in col name.
first_match = df.Tunnel ID.str.contains('ic').idxmax()
# Would ideally return index: 1; containing ID: 'Dick'.
那么一個人試圖使用什么pd.Series.str.contains()并且pd.Series包含空格呢?
uj5u.com熱心網友回復:
您還可以通過索引到您的資料框而不使用點符號來訪問您的列。所以就這樣做
first_match = df["Tunnel ID"].str.contains('ic').idxmax()
你應該很高興
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414788.html
標籤:
