詳解如何利用pandas進(jìn)行數(shù)據(jù)行轉(zhuǎn)列和列轉(zhuǎn)行
更新時間:2024年04月01日 16:57:47 作者:懸崖上的金魚
這篇文章主要為大家詳細(xì)介紹了如何利用pandas進(jìn)行數(shù)據(jù)行轉(zhuǎn)列和列轉(zhuǎn)行,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
一、數(shù)據(jù)列轉(zhuǎn)行
import pandas as pd # 導(dǎo)入 pandas 庫
def pivot_excel_data(input_file, output_file):
"""
將 Excel 文件中的數(shù)據(jù)行轉(zhuǎn)換為列,并保存為新的 Excel 文件
Parameters:
input_file (str): 輸入的 Excel 文件路徑
output_file (str): 輸出的 Excel 文件路徑
Returns:
None
"""
# 讀取 Excel 數(shù)據(jù)
df = pd.read_excel(input_file, sheet_name='Sheet1')
# 使用 pivot_table() 函數(shù)將數(shù)據(jù)行轉(zhuǎn)換為列
df_pivot = df.pivot_table(index='店鋪', columns='新費用類型', values='金額').reset_index()
# 將處理后的數(shù)據(jù)保存到新的 Excel 文件
df_pivot.to_excel(output_file, index=False)
# 調(diào)用函數(shù)進(jìn)行數(shù)據(jù)處理
input_file = 'C:\\Users\\Administrator\\Desktop\\新數(shù)據(jù)_處理后.xlsx'
output_file = 'converted_data.xlsx'
pivot_excel_data(input_file, output_file)二、數(shù)據(jù)行轉(zhuǎn)列
import pandas as pd # 導(dǎo)入 pandas 庫
def melt_excel_data(input_file, output_file):
"""
將 Excel 文件中的數(shù)據(jù)列轉(zhuǎn)換為行,并保存為新的 Excel 文件
Parameters:
input_file (str): 輸入的 Excel 文件路徑
output_file (str): 輸出的 Excel 文件路徑
Returns:
None
"""
# 讀取 Excel 數(shù)據(jù)
df = pd.read_excel(input_file, sheet_name='Sheet1')
# 使用 melt() 函數(shù)將數(shù)據(jù)列轉(zhuǎn)換為行
df_melted = df.melt(id_vars=['店鋪'], var_name='費用類型', value_name='金額')
# 將處理后的數(shù)據(jù)保存到新的 Excel 文件
df_melted.to_excel(output_file, index=False)
# 調(diào)用函數(shù)進(jìn)行數(shù)據(jù)處理
input_file = 'C:\\Users\\Administrator\\Desktop\\converted_data.xlsx'
output_file = 'converted_data2.xlsx'
melt_excel_data(input_file, output_file)到此這篇關(guān)于詳解如何利用pandas進(jìn)行數(shù)據(jù)行轉(zhuǎn)列和列轉(zhuǎn)行的文章就介紹到這了,更多相關(guān)pandas行列互轉(zhuǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳細(xì)解析Python中__init__()方法的高級應(yīng)用
這篇文章主要介紹了詳細(xì)解析Python中__init__()方法的高級應(yīng)用,包括在映射和elif序列等地方的更為復(fù)雜的用法,需要的朋友可以參考下2015-05-05
Python使用win32com模塊實現(xiàn)數(shù)據(jù)庫表結(jié)構(gòu)自動生成word表格的方法
這篇文章主要介紹了Python使用win32com模塊實現(xiàn)數(shù)據(jù)庫表結(jié)構(gòu)自動生成word表格的方法,結(jié)合實例形式分析了win32com模塊下載、連接mysql、查詢獲取表結(jié)構(gòu)以及使用win32com生成word表格的相關(guān)操作技巧,需要的朋友可以參考下2018-07-07
jupyter 使用Pillow包顯示圖像時inline顯示方式
這篇文章主要介紹了jupyter 使用Pillow包顯示圖像時inline顯示方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

