英文:
Pandas Query astype(str)
问题
我有一个包含通常只有数字的列的数据框。偶尔会包含文本值,这意味着它的类型将是“object”而不是“int64”。我试图执行一个查询,将该值与整数的字符串值进行比较,而不是执行ColumnA == "100" & ColumnA == 100
。以下是我尝试的查询语句:
df.query('ColumnA.astype(str) == "100"')
但这会导致一个KeyError
,指示str
键不存在。
在Pandas查询中是否有一种使用astype
的方法?
英文:
I have a dataframe that has a column that usually has numbers only. On occasion, it will have text values, which means it will be of type object
instead int64
. Instead of doing ColumnA == "100" & ColumnA == 100
I am trying to perform a query that will compare the value to the string value of an integer:
df.query('ColumnA.astype(str) == "100"))
But this gives me a KeyError
saying the str
key does not exist.
Is there a way to use astype
within a Pandas query?
答案1
得分: 3
虽然在这种用例中您不需要query
,但您应该用引号括起str
:
df = pd.DataFrame({"ColumnA": ["100", 200, "300", 400, 100, "500"]})
out = df.query('ColumnA.astype("str") == "100"')
输出:
print(out)
ColumnA
0 100
4 100
英文:
Although you don't need query
in this kind of usecases, you should enclose str
with quotes :
df = pd.DataFrame({"ColumnA": ["100", 200, "300", 400, 100, "500"]})
out = df.query('ColumnA.astype("str") == "100"')
Output :
print(out)
ColumnA
0 100
4 100
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论