Browse Source

Python manipulation

Petra Lamborn 5 years ago
parent
commit
468b5ed1ee
3 changed files with 79 additions and 0 deletions
  1. 23
    0
      py/clustering.py
  2. 0
    0
      py/dbtest.py
  3. 56
    0
      py/util.py

+ 23
- 0
py/clustering.py View File

@@ -0,0 +1,23 @@
1
+from util import getQuery
2
+import pandas as p
3
+import matplotlib.pyplot as plt
4
+import seaborn as sns
5
+
6
+
7
+query = """
8
+SELECT icp_id, read_date + CONCAT(period / 2, ':', period %% 2 * 30, ':00')::time AS read_time,
9
+    kwh_tot
10
+FROM public.coup_tall_april WHERE icp_id LIKE (%s) ORDER BY icp_id, read_time;
11
+"""
12
+
13
+qparams = ['%%1117']
14
+
15
+df = getQuery(query, qparams)
16
+
17
+print(df.info())
18
+
19
+sns.set()
20
+
21
+sns.scatterplot(x = 'read_time', y = 'kwh_tot', hue = 'icp_id', style = 'icp_id', data = df)
22
+
23
+plt.show()

dbtest.py → py/dbtest.py View File


+ 56
- 0
py/util.py View File

@@ -0,0 +1,56 @@
1
+import psycopg2 as pg
2
+from configparser import ConfigParser
3
+import pandas.io.sql as psql
4
+
5
+def config(filename='database.ini', section='postgresql'):
6
+    """Config parser from http://www.postgresqltutorial.com/postgresql-python/connect/"""
7
+    # create a parser
8
+    parser = ConfigParser()
9
+    # read config file
10
+    parser.read(filename)
11
+ 
12
+    # get section, default to postgresql
13
+    db = {}
14
+    if parser.has_section(section):
15
+        params = parser.items(section)
16
+        for param in params:
17
+            db[param[0]] = param[1]
18
+    else:
19
+        raise Exception('Section {0} not found in the {1} file'.format(section, filename))
20
+ 
21
+    return db
22
+
23
+def getQuery(query, qparams = []):
24
+    """
25
+    Get single query
26
+    """
27
+    conn = False
28
+
29
+    try:
30
+        params = config()
31
+
32
+        print("Connecting to database")
33
+
34
+        conn = pg.connect(**params)
35
+        cur = conn.cursor()
36
+
37
+        # Get table
38
+        dataframe = psql.read_sql(query, conn, params = qparams)
39
+
40
+        cur.close()
41
+
42
+        return dataframe
43
+
44
+    except (Exception, pg.DatabaseError) as error:
45
+        print(error)
46
+        return None
47
+
48
+    finally:
49
+        if conn is not False:
50
+            conn.close()
51
+            print('Database connection closed')
52
+
53
+if __name__ == "__main__":
54
+    dv = getQuery('SELECT version()').version[0]
55
+    print('PostgreSQL database version:')
56
+    print(dv)