Python Pandas - 熔化



Pandas 中的熔化是指將 DataFrame 從寬格式轉換為長格式的過程。在寬格式中,資料分佈在多個列中。簡單來說,它會“反轉”DataFrame 的列為行,這對於視覺化和對資料集執行統計分析很有用。

Pandas 庫提供了melt()wide_to_long() 函式,用於將 DataFrame 從寬格式轉換為長格式。在本教程中,我們將學習 Pandas 中的melt()wide_to_long() 函式,以及如何使用這兩種方法將 DataFrame 從寬格式轉換為長格式。

Pandas 中的熔化

Pandas 中的melt() 函式將寬 DataFrame 轉換為長格式。這只不過是“反轉”DataFrame。

示例

以下示例演示了使用pandas.melt() 函式熔化一個簡單的 DataFrame。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},'B': {0: 1, 1: 3, 2: 5},'C': {0: 2, 1: 4, 2: 6}})

# Display the input DataFrame
print('Input DataFrame:\n', df)

# Melt the DataFrame
melted_df = pd.melt(df, id_vars=['A'], value_vars=['B'])

print('Output melted DataFrame:\n', melted_df)

以下是上述程式碼的輸出 -

Input DataFrame:
ABC
0a12
1b34
2c56
Output melted DataFrame:
Avariablevalue
0aB1
1bB3
2cB5

示例:在熔化時處理索引值

此示例演示了在使用pandas.melt() 函式熔化 DataFrame 時如何處理缺失值。

import pandas as pd

# Create a DataFrame
index = pd.MultiIndex.from_tuples([("person", "A"), ("person", "B")])
df= pd.DataFrame({
"first": ["John", "Mary"],"last": ["Doe", "Bo"],
"height": [5.5, 6.0],"weight": [130, 150]}, index=index)

# Display the input DataFrame
print('Input DataFrame:\n', df)

# Melt the DataFrame
melted_df = pd.melt(df, id_vars=["first", "last"], ignore_index=False)

print('Output melted DataFrame:\n', melted_df)

以下是上述程式碼的輸出 -

Input DataFrame:
firstlastheightweight
personAJohnDoe5.5130
BMaryBo6.0150
Output melted DataFrame:
firstlastvariablevalue
personAJohnDoeheight5.5
BMaryBoheight6.0
AJohnDoeweight130.0
BMaryBoweight150.0

使用 wide_to_long() 熔化

pandas wide_to_long() 函式提供了對轉換的更多控制。當您的列具有包含字尾的結構化命名模式時,它很有用。

示例

此示例使用wide_to_long() 函式執行高階熔化轉換。

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],
'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],
'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]})

# Display the input DataFrame
print('Input DataFrame:\n', df)

# Melt the DataFrame using wide_to_long()
long_df = pd.wide_to_long(df, stubnames='ht', i=['famid', 'birth'], j='age')

print('Output Long Melted DataFrame:\n', long_df)

以下是上述程式碼的輸出 -

Input DataFrame:
famidbirthht1ht2
0112.83.4
1122.93.8
2132.22.9
3212.03.2
4221.82.8
5231.92.4
6312.23.3
7322.33.4
8332.12.9
Output Long Melted DataFrame:
ht
famidbirthage
1112.8
23.4
212.9
23.8
312.2
22.9
2112.0
23.2
211.8
22.8
311.9
22.4
3112.2
23.3
212.3
23.4
312.1
22.9
廣告