Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在rpy2中使用python中的变量?_Python_R_Rpy2 - Fatal编程技术网

如何在rpy2中使用python中的变量?

如何在rpy2中使用python中的变量?,python,r,rpy2,Python,R,Rpy2,我的简单程序从Python中提取数据库并存储在变量行中 cursor = con.cursor() cursor.execute("SELECT * FROM traffic") #Retrieves data from SQL rows = cursor.fetchall() for row in rows: row = list(row) a = row[1:] b = row[:-1]

我的简单程序从Python中提取数据库并存储在变量行中

cursor = con.cursor()       
    cursor.execute("SELECT * FROM traffic")

    #Retrieves data from SQL
    rows = cursor.fetchall()  

    for row in rows:
       row = list(row)
       a = row[1:]
       b = row[:-1]
       print(a)
       print(b)
现在我可以得到列表a和b中的月份和流量,如[1000L]

['January']
[100L]
['February']
[10430L]
['March']
[1500L]
['April']
[100L]
['May']
[1200L]
['June']
[800L]
['July']
[8000L]
['August']
[100000L]
['September']
现在我想从中画出柱状图和柱状图。 该行包含两个列:
MOnth
Traffic
。我想使用Rpy2将其转换为图表。我该怎么做?这是我的桌子:

month     | traffic |
+-----------+---------+
| January   |    1000 |
| February  |     100 |
| March     |   10430 |
| April     |    1500 |
| May       |     100 |
| June      |    1200 |
| July      |     800 |
| August    |    8000 |
| September |  100000 |
+-----------+---------+

首先,从数据库中列出两个列表。比如:

cursor = con.cursor()       
cursor.execute("SELECT * FROM traffic")

#Retrieves data from SQL
rows = cursor.fetchall()  

Month = list()
Traffic = list()

for row in rows:
    Month.append(row['Month'])          # guesswork - what does a row look like?
    Traffic.append(row['Traffic'])
然后,现在有了两个python列表,可以这样绘制一个图:

>>> r.plot(Month,Traffic)
rpy2.rinterface.NULL
您可能需要以下行:

>>> r.plot(Month,Traffic,type="l")
rpy2.rinterface.NULL
您可能需要漂亮的标签:

>>> r.plot(Month,Traffic,type="l",xlab="Month",ylab="Traffic")

什么是“图表”(tam ta daaaam)?听起来很吓人。我查阅了一些教程,发现:从Python空间变量尝试,没有成功!简单地说,我尝试了r.x11()r('plot(row)')。如果您只想进行绘图,那么您可以在Python中(使用matplotlib)进行所有操作。不,我想进行复杂的操作。我正处于学习阶段,所以决定先做一些小事情。月和流量是两个冒号。首先,我提取了行中的数据!我想把行变量转换成R变量,再转换成图表。尝试了r('绘图(行)'),不起作用!它是静态的。我知道怎么做。我被困在动态的一个。使用Python从数据库中提取数据并打印这些提取数据的图表。嗯?所以真正的问题是“如何将数据库中的列读入python列表?”然后问这个问题。不,您想要绘制它们。要绘制它们,必须从数据库中迭代获取的行对象中生成python列表。虽然我们可以读取您的代码,但如果没有像您这样的数据库,我们就无法运行它。我遇到了这样的错误:TypeError:元组索引必须是整数,而不是str。我认为list方法没有将元组(默认值)转换为list。我试过这样做:行中的行:行=列表(行)a=行[1:]b=行[:-1]打印(a)打印(b)工作,但r绘图(a,b)不工作