詳解如何利用pandas進(jìn)行數(shù)據(jù)行轉(zhuǎn)列和列轉(zhuǎn)行
一、數(shù)據(jù)列轉(zhuǎn)行
import pandas as pd # 導(dǎo)入 pandas 庫(kù) 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='新費(fèi)用類型', 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 庫(kù) 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='費(fèi)用類型', 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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Python小波分析庫(kù)Pywavelets的一點(diǎn)使用心得
這篇文章主要介紹了淺談Python小波分析庫(kù)Pywavelets的一點(diǎn)使用心得,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python簡(jiǎn)單實(shí)現(xiàn)TCP包發(fā)送十六進(jìn)制數(shù)據(jù)的方法
這篇文章主要介紹了Python簡(jiǎn)單實(shí)現(xiàn)TCP包發(fā)送十六進(jìn)制數(shù)據(jù)的方法,結(jié)合實(shí)例形式簡(jiǎn)單分析了Python實(shí)現(xiàn)TCP數(shù)據(jù)傳輸及發(fā)送十六進(jìn)制數(shù)據(jù)包的相關(guān)技巧,需要的朋友可以參考下2016-04-04Python?Flask?實(shí)現(xiàn)?HTML?文件壓縮案例代碼(9?級(jí)壓縮)
這篇文章主要介紹了Python?Flask?實(shí)現(xiàn)?HTML?文件壓縮案例代碼(9?級(jí)壓縮),本案例是基于?Python?Flask?進(jìn)行搭建,所以需要提前搭建一個(gè)?Flask?項(xiàng)目環(huán)境,有?app.py?文件和?templates/index.html?文件即可,需要的朋友可以參考下2023-01-01基于Python中numpy數(shù)組的合并實(shí)例講解
下面小編就為大家分享一篇基于Python中numpy數(shù)組的合并實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04Python內(nèi)置函數(shù)delattr的具體用法
本篇文章主要介紹了Python內(nèi)置函數(shù)delattr的具體用法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11