我需要修剪查詢字串中的“我的寵物”列。怎么可能呢?
# Note that one cat literal has a trailing space.
testDF = pd.DataFrame([{"My Pet":"cat ", "Cost":"$10 ", "Weight":"10 pounds", "Name":"Violet"},
{"My Pet":"cat", "Cost":"$10 ", "Weight":"15 pounds", "Name":"Sirius"},
{"My Pet":"dog", "Cost":"$0 ", "Weight":"50 pounds", "Name":"Sam"},
{"My Pet":"turtle", "Cost":"$5 ", "Weight":"20 ounces", "Name":"Tommy"},
])
# We try to filter on cat.
catDF = testDF.query("`My Pet` == 'cat'") # This yields only one row because one cat cell has a trailing space
catDF.head()
輸出只有一行,但我想在兩行中都包含 cat
My Pet Cost Weight Name
1 cat $10 15 pounds Sirius
uj5u.com熱心網友回復:
使用Series.str.strip,但需要engine="python":
catDF = testDF.query("`My Pet`.str.strip() == 'cat'", engine="python")
print (catDF)
My Pet Cost Weight Name
0 cat $10 10 pounds Violet
1 cat $10 15 pounds Sirius
uj5u.com熱心網友回復:
您可以訪問字串系列的字串方法。這意味著您可以使用該Series.str.strip功能來清除空格。
testDF["My Pet"] = testDF["My Pet"].str.strip()
如果您只想清除尾隨空格,請使用rstrip(和lstrip前導空格)
您可以選擇指定要顯式洗掉的字符集。例如,僅洗掉空格和制表符:
testDF["My Pet"] = testDF["My Pet"].str.strip(" \t")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/527448.html
標籤:Python熊猫数据框
