UPDATE函数在Python中的sqldf中

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

UPDATE function in sqldf in Python

问题

在Python平台中使用'from pandasql import sqldf'构建SQL代码。执行下面的代码,结果输出为"没有这样的表df"。有人能够纠正吗?

query = """
UPDATE df
SET C = C * 10
WHERE C < 50
"""
英文:

Building SQL code in Python platform using 'from pandasql import sqldf'.
Executed code below and it turned out to be "no such table df" as output.
Anyone able to rectify it?

query=&quot;&quot;&quot;
UPDATE df
SET C = C*10
WHERE C &lt;50
&quot;&quot;&quot;

答案1

得分: 1

pandasql不支持更新操作,您需要使用类似以下方式:

from pandasql import sqldf
import pandas as pd

df = pd.DataFrame({
   'A': ['foo', 'bar', 'baz', 'foo', 'bar', 'baz'],
   'B': ['one', 'one', 'two', 'three', 'two', 'two'],
   'C': [10, 20, 30, 40, 50, 60],
   'D': [7, 8, 9, 10, 11, 12]
})

query = """
SELECT *
FROM df
WHERE column1 > 10;
"""

result = sqldf(query, globals())

result.loc[result['C'] < 50, 'C'] *= 10
英文:

pandasql does not support update operations, you need to use something like this:

from pandasql import sqldf
import pandas as pd

df = pd.DataFrame({
   &#39;A&#39;: [&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;, &#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;],
   &#39;B&#39;: [&#39;one&#39;, &#39;one&#39;, &#39;two&#39;, &#39;three&#39;, &#39;two&#39;, &#39;two&#39;],
   &#39;C&#39;: [10, 20, 30, 40, 50, 60],
   &#39;D&#39;: [7, 8, 9, 10, 11, 12]
})

query = &quot;&quot;&quot;
SELECT *
FROM df
WHERE column1 &gt; 10;
&quot;&quot;&quot;

result = sqldf(query, globals())

result.loc[result[&#39;C&#39;] &lt; 50, &#39;C&#39;] *= 10

huangapple
  • 本文由 发表于 2023年6月22日 07:32:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527753.html
匿名

发表评论

匿名网友

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

确定