Pandas 查询 astype(str)

huangapple go评论54阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月17日 23:37:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273844.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定