Skip to content

Instantly share code, notes, and snippets.

@RockfordWei
Created July 27, 2018 12:54
Show Gist options
  • Save RockfordWei/d28b35b8e438ca6a8c5d958d5d040bb0 to your computer and use it in GitHub Desktop.
Save RockfordWei/d28b35b8e438ca6a8c5d958d5d040bb0 to your computer and use it in GitHub Desktop.
MySQL query transpose and pivot
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" year month value\n",
"0 2001 1 123\n",
"1 2002 2 234\n",
"2 2003 3 345\n"
]
}
],
"source": [
"import pandas as pd\n",
"from sqlalchemy import create_engine\n",
"\n",
"dbconnection = create_engine(\"mysql://root:rockford@medec.ruby/test\")\n",
"matrix = pd.read_sql(\"SELECT * FROM matrix\", dbconnection)\n",
"print(matrix)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" 0 1 2\n",
"year 2001 2002 2003\n",
"month 1 2 3\n",
"value 123 234 345\n"
]
}
],
"source": [
"m = matrix.transpose()\n",
"print(m)"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"month 1 2 3\n",
"year \n",
"2001 123.0 NaN NaN\n",
"2002 NaN 234.0 NaN\n",
"2003 NaN NaN 345.0\n"
]
}
],
"source": [
"n = matrix.pivot(index=\"year\", columns=\"month\", values=\"value\")\n",
"print(n)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment