Customer - Segmentation - Jupyter Notebook
Customer - Segmentation - Jupyter Notebook
Flask
In [2]: 1 app=Flask(__name__)
Read dataset
In [3]: 1 df=pd.read_csv('customer_segmentation.csv')
2 df.head()
Out[3]:
customer_id qtt_order total_spent last_order
In [4]: 1 df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 100000 entries, 0 to 99999
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 customer_id 100000 non-null int64
1 qtt_order 100000 non-null int64
2 total_spent 100000 non-null float64
3 last_order 100000 non-null object
dtypes: float64(1), int64(2), object(1)
memory usage: 3.1+ MB
In [5]: 1 db_config = {
2 'host': 'localhost',
3 'user': 'root',
4 'password': '050501@Aks',
5 'database': 'akashdb',
6 }
7
8 def connect_and_insert_data(filename):
9 try:
10 connection = mysql.connector.connect(**db_config)
11
12 if connection.is_connected():
13 cursor = connection.cursor()
14
15 for index, row in df.iterrows():
16 cursor.execute("""
17 INSERT INTO cus_seg (
18 customer_id, qtt_order, total_spent,
19 last_order
20 ) VALUES (%s, %s, %s, %s)
21 """, (
22 row['customer_id'], row['qtt_order'], row['total_sp
23 row['last_order']
24 ))
25
26 connection.commit()
27
28 except Error as e:
29 print("Error:", e)
30
31 finally:
32 if connection.is_connected():
33 cursor.close()
34 connection.close()
35
36 @app.route('/insert_data')
37 def insert_data():
38 filename = 'customer_segmentation.csv'
39 connect_and_insert_data(filename)
40 return jsonify({'message': 'Data inserted successfully'})
41
42 if __name__ == '__main__':
43 app.run(debug=False)
API to do SQL
In [7]: 1 db = pymysql.connect(**db_config)
2 cursor = db.cursor()
3
4 @app.route('/api/data', methods=['GET'])
5 def get_users():
6 try:
7 cursor.execute("SELECT * FROM cus_seg LIMIT 20")
8 users = cursor.fetchall()
9
10 user_list = '<br>'.join([f'{user[0]}, {user[1]}, {user[2]}, {us
11
12 return user_list
13
14 except Exception as e:
15 return str(e)
16
17 if __name__ == '__main__':
18 app.run(debug=False)
19