Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to convert python two-dimensional table to one-dimensional table

Shulou Source: shulou.com Published: 2022-05-31 14:02:32 10月03日 Update

This article mainly explains the "python two-dimensional table how to convert into one-dimensional table", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "python two-dimensional table how to convert into one-dimensional table" bar!

# load data import pandas as pddf_old1 = pd.read_excel (r "D:\ Jupyter\ data\ Python.xlsx", sheet_name = "change one dimension") df_old1

# data cleaning, set the first column to index column df_old2 = pd.read_excel (r "D:\ Jupyter\ data\ Python.xlsx", sheet_name = "change one dimension", index_col = 0) df_old2

# reset index df_old3 = df_old2.reset_index () df_old3

Convert column names to column data

Here we need to use the .melt () function of pandas. Melt () is a reverse operation function that converts column names into column data (columns_name → column_values) and reconstructs DataFrame as follows:

The data3=data2.melt (id_vars='index', var_name='year',value_name='stu_num') data3 parameter explains: DataFrame: the dataset to be processed; id_vars: the column name that does not need to be converted; value_vars: the column name to be converted, if all the remaining columns need to be converted; var_name and value_name are the column names corresponding to the custom settings; col_level: use this level if the column is MultiIndex.

The results are as follows:

# convert 2D to 1D DF _ new = df_old3.melt (id_vars = "index", var_name = "year", value_name = "sales") df_new

The last step is in place:

# one step import pandas as pddf_melt = pd.read_excel (r "D:\ Jupyter\ data\ Python.xlsx", sheet_name = "change one dimension", index_col = 0) .reset_index () .melt (id_vars = "index", var_name = "year", value_name = "sales") .rename (columns = {"index": "province"}) df_melt

Thank you for your reading, the above is the content of "how to convert a python two-dimensional table into an one-dimensional table". After the study of this article, I believe you have a deeper understanding of how to convert a two-dimensional python table into an one-dimensional table. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: Tables one-dimensional two-dimensional data learning one-step content function year index sales sales no parameters that is ideas situations articles more provinces Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi MySQL Linux macOS vpn