Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Melt in pandas

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Xiaobian to share with you how to use Melt in pandas, I believe most people still do not know how to use, so share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!

Melt

Melt is used to turn a wide table into a narrow table. It is a pivot inversion operation function, converting column names into column data (column name → column values) and reconstructing DataFrame.

Simply put, the specified column is placed on the spread row to become two columns, the category is variable(can be specified) column, the value is value(can be specified) column.

Usage:

pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)

Parameter function:

Frame: It means DataFrame.

id_vars [tuple, list or ndarray, optional]: column names that do not need to be converted, reference columns used as identifier variables

value_vars [tuple, list or ndarray, optional]: Reference columns to be unpivoted. If not specified, use all columns not set to id_vars

var_name [scalar]: refers to the name used for the "variable" column. If None, use- - frame.columns.name or 'variable'

value_name [scalar, default 'value']: refers to the name used for the column' value '

col_level [int or string, optional]: If listed as MultiIndex, it will use this level to melt

For example, there is a string of data representing different cities and daily population movements:

import pandas as pd df1 = pd.DataFrame({'city': {0: 'a', 1: 'b', 2: 'c'}, 'day1': {0: 1, 1: 3, 2: 5}, 'day2': {0: 2, 1: 4, 2: 6}}) df1

Now turn the day1 and day2 columns into variable columns and add a value column:

pd.melt(df1, id_vars=['city'])

The above is all the content of this article "how to use Melt in pandas", thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report