


How to implement pivot() in pandas.DataFrame to convert rows to columns (code)
The content of this article is about how pivot() in pandas.DataFrame implements row conversion (code). It has certain reference value. Friends in need can refer to it. I hope It will help you.
Example:
The following table needs to be converted between rows and columns:
The code is as follows:
# -*- coding:utf-8 -*- import pandas as pd import MySQLdb from warnings import filterwarnings # 由于create table if not exists总会抛出warning,因此使用filterwarnings消除 filterwarnings('ignore', category = MySQLdb.Warning) from sqlalchemy import create_engine import sys if sys.version_info.major<3: reload(sys) sys.setdefaultencoding("utf-8") # 此脚本适用于python2和python3 host,port,user,passwd,db,charset="192.168.1.193",3306,"leo","mysql","test","utf8" def get_df(): global host,port,user,passwd,db,charset conn_config={"host":host, "port":port, "user":user, "passwd":passwd, "db":db,"charset":charset} conn = MySQLdb.connect(**conn_config) result_df=pd.read_sql('select UserName,Subject,Score from TEST',conn) return result_df def pivot(result_df): df_pivoted_init=result_df.pivot('UserName','Subject','Score') df_pivoted = df_pivoted_init.reset_index() # 将行索引也作为DataFrame值的一部分,以方便存储数据库 return df_pivoted_init,df_pivoted # 返回的两个DataFrame,一个是以姓名作index的,一个是以数字序列作index,前者用于unpivot,后者用于save_to_mysql def unpivot(df_pivoted_init): # unpivot需要进行df_pivoted_init二维表格的行、列索引遍历,需要拼SQL因此不能使用save_to_mysql存数据,这里使用SQL和MySQLdb接口存 insert_sql="insert into test_unpivot(UserName,Subject,Score) values " # 处理值为NaN的情况 df_pivoted_init=df_pivoted_init.add(0,fill_value=0) for col in df_pivoted_init.columns: for index in df_pivoted_init.index: value=df_pivoted_init.at[index,col] if value!=0: insert_sql=insert_sql+"('%s','%s',%s)" %(index,col,value)+',' insert_sql = insert_sql.strip(',') global host, port, user, passwd, db, charset conn_config = {"host": host, "port": port, "user": user, "passwd": passwd, "db": db, "charset": charset} conn = MySQLdb.connect(**conn_config) cur=conn.cursor() cur.execute("create table if not exists test_unpivot like TEST") cur.execute(insert_sql) conn.commit() conn.close() def save_to_mysql(df_pivoted,tablename): global host, port, user, passwd, db, charset """ 只有使用sqllite时才能指定con=connection实例,其他数据库需要使用sqlalchemy生成engine,engine的定义可以添加?来设置字符集和其他属性 """ conn="mysql://%s:%s@%s:%d/%s?charset=%s" %(user,passwd,host,port,db,charset) mysql_engine = create_engine(conn) df_pivoted.to_sql(name=tablename, con=mysql_engine, if_exists='replace', index=False) # 从TEST表读取源数据至DataFrame结构 result_df=get_df() # 将源数据行转列为二维表格形式 df_pivoted_init,df_pivoted=pivot(result_df) # 将二维表格形式的数据存到新表test中 save_to_mysql(df_pivoted,'test') # 将被行转列的数据unpivot,存入test_unpivot表中 unpivot(df_pivoted_init)
The result is as follows:
About the pivot method that comes with the Pandas DataFrame class:
DataFrame.pivot(index=None, columns=None , values=None):
Return reshaped DataFrame organized by given index / column values.
There are only 3 parameters here because pivot The subsequent result must be a two-dimensional table, which only requires rows and columns and their corresponding values. And because it is a two-dimensional table, the is_pass column will definitely be lost after unpivot, so I did not check this column at the beginning.
The above is the detailed content of How to implement pivot() in pandas.DataFrame to convert rows to columns (code). For more information, please follow other related articles on the PHP Chinese website!

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor