Python分析和處理excel文件數(shù)據(jù)的詳細(xì)步驟
一、準(zhǔn)備工作
1. 安裝必要的庫(kù)
首先需要安裝 Python 的數(shù)據(jù)處理和 Excel 處理庫(kù):
pip install pandas openpyxl xlrd
注意:
pandas是核心數(shù)據(jù)處理庫(kù)openpyxl用于處理.xlsx格式的 Excel 文件xlrd用于處理較舊的.xls格式(從 xlrd 2.0.0 開(kāi)始不再支持 .xlsx)
2. 準(zhǔn)備 Excel 文件
假設(shè)我們有一個(gè)名為 sales_data.xlsx 的 Excel 文件,包含以下數(shù)據(jù):
| 日期 | 產(chǎn)品 | 銷量 | 單價(jià) | 銷售額 |
|---|---|---|---|---|
| 2023-01-01 | 產(chǎn)品A | 10 | 100 | 1000 |
| 2023-01-01 | 產(chǎn)品B | 5 | 200 | 1000 |
| 2023-01-02 | 產(chǎn)品A | 8 | 100 | 800 |
| 2023-01-02 | 產(chǎn)品C | 12 | 150 | 1800 |
| ... | ... | ... | ... | ... |
二、讀取 Excel 文件
1. 使用 pandas 讀取
import pandas as pd
# 讀取整個(gè)工作表
df = pd.read_excel('sales_data.xlsx')
# 顯示前5行數(shù)據(jù)
print(df.head())
# 讀取特定工作表(如果有多個(gè)工作表)
# df = pd.read_excel('sales_data.xlsx', sheet_name='Sheet1')
# 讀取特定列
# df = pd.read_excel('sales_data.xlsx', usecols=['日期', '產(chǎn)品', '銷量'])2. 使用 openpyxl 讀取
from openpyxl import load_workbook
# 加載工作簿
wb = load_workbook('sales_data.xlsx')
# 獲取活動(dòng)工作表或指定工作表
sheet = wb.active # 或 wb['Sheet1']
# 讀取數(shù)據(jù)
data = []
for row in sheet.iter_rows(values_only=True):
data.append(row)
# 轉(zhuǎn)換為DataFrame(可選)
import pandas as pd
df = pd.DataFrame(data[1:], columns=data[0]) # 假設(shè)第一行是標(biāo)題三、數(shù)據(jù)基本操作
1. 查看數(shù)據(jù)信息
# 查看數(shù)據(jù)基本信息 print(df.info()) # 查看統(tǒng)計(jì)摘要 print(df.describe()) # 查看列名 print(df.columns.tolist())
2. 數(shù)據(jù)篩選
# 篩選特定日期的數(shù)據(jù) jan_data = df[df['日期'] == '2023-01-01'] # 篩選銷量大于5的產(chǎn)品 high_sales = df[df['銷量'] > 5] # 篩選多個(gè)條件 filtered_data = df[(df['日期'] >= '2023-01-01') & (df['產(chǎn)品'] == '產(chǎn)品A')]
3. 數(shù)據(jù)分組和聚合
# 按產(chǎn)品分組計(jì)算總銷量和總銷售額
product_stats = df.groupby('產(chǎn)品').agg({
'銷量': 'sum',
'銷售額': 'sum'
}).reset_index()
print(product_stats)
# 計(jì)算每日銷售額總和
daily_sales = df.groupby('日期')['銷售額'].sum().reset_index()4. 數(shù)據(jù)排序
# 按銷售額降序排序
sorted_data = df.sort_values('銷售額', ascending=False)
# 按日期和銷量排序
sorted_data = df.sort_values(['日期', '銷量'], ascending=[True, False])四、數(shù)據(jù)可視化
1. 使用 matplotlib 繪制圖表
import matplotlib.pyplot as plt
# 設(shè)置中文字體(避免中文顯示問(wèn)題)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
# 繪制柱狀圖 - 各產(chǎn)品總銷量
product_stats.plot(kind='bar', x='產(chǎn)品', y='銷量', title='各產(chǎn)品總銷量')
plt.ylabel('銷量')
plt.show()
# 繪制折線圖 - 每日銷售額趨勢(shì)
daily_sales.plot(kind='line', x='日期', y='銷售額', title='每日銷售額趨勢(shì)')
plt.xlabel('日期')
plt.ylabel('銷售額')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()2. 使用 seaborn 進(jìn)行高級(jí)可視化
pip install seaborn
import seaborn as sns
# 設(shè)置風(fēng)格
sns.set(style="whitegrid")
# 繪制箱線圖 - 各產(chǎn)品銷量分布
plt.figure(figsize=(10, 6))
sns.boxplot(x='產(chǎn)品', y='銷量', data=df)
plt.title('各產(chǎn)品銷量分布')
plt.show()
# 繪制熱力圖 - 相關(guān)性分析
corr_matrix = df[['銷量', '單價(jià)', '銷售額']].corr()
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm')
plt.title('變量相關(guān)性熱力圖')
plt.show()五、數(shù)據(jù)處理與清洗
1. 處理缺失值
# 檢查缺失值
print(df.isnull().sum())
# 填充缺失值
df_filled = df.fillna({'銷量': 0, '單價(jià)': df['單價(jià)'].mean()})
# 刪除包含缺失值的行
df_dropped = df.dropna()2. 數(shù)據(jù)類型轉(zhuǎn)換
# 轉(zhuǎn)換日期格式 df['日期'] = pd.to_datetime(df['日期']) # 轉(zhuǎn)換數(shù)值類型 df['銷量'] = pd.to_numeric(df['銷量'], errors='coerce') df['單價(jià)'] = pd.to_numeric(df['單價(jià)'], errors='coerce') df['銷售額'] = pd.to_numeric(df['銷售額'], errors='coerce')
3. 數(shù)據(jù)標(biāo)準(zhǔn)化
from sklearn.preprocessing import StandardScaler # 選擇需要標(biāo)準(zhǔn)化的列 features = df[['銷量', '單價(jià)', '銷售額']] # 標(biāo)準(zhǔn)化處理 scaler = StandardScaler() scaled_features = scaler.fit_transform(features) # 轉(zhuǎn)換回DataFrame scaled_df = pd.DataFrame(scaled_features, columns=features.columns)
六、高級(jí)分析技術(shù)
1. 時(shí)間序列分析
# 確保日期是datetime類型
df['日期'] = pd.to_datetime(df['日期'])
# 設(shè)置日期為索引
df.set_index('日期', inplace=True)
# 按周匯總銷售額
weekly_sales = df.resample('W')['銷售額'].sum()
# 移動(dòng)平均
df['7天移動(dòng)平均銷售額'] = df['銷售額'].rolling(window=7).mean()2. 相關(guān)性分析
# 計(jì)算相關(guān)性矩陣
corr_matrix = df[['銷量', '單價(jià)', '銷售額']].corr()
# 可視化相關(guān)性
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', center=0)
plt.title('變量相關(guān)性熱力圖')
plt.show()3. 分組聚合與透 視表
# 使用groupby分組聚合
grouped = df.groupby(['產(chǎn)品', '日期']).agg({
'銷量': 'sum',
'銷售額': 'sum'
}).reset_index()
# 創(chuàng)建透 視表
pivot_table = df.pivot_table(
values='銷售額',
index='日期',
columns='產(chǎn)品',
aggfunc='sum',
fill_value=0
)
print(pivot_table)七、完整示例
下面是一個(gè)完整的分析流程示例:
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
# 1. 讀取數(shù)據(jù)
df = pd.read_excel('sales_data.xlsx')
# 2. 數(shù)據(jù)清洗
df['日期'] = pd.to_datetime(df['日期'])
df['銷量'] = pd.to_numeric(df['銷量'], errors='coerce').fillna(0)
df['單價(jià)'] = pd.to_numeric(df['單價(jià)'], errors='coerce').fillna(df['單價(jià)'].mean())
df['銷售額'] = pd.to_numeric(df['銷售額'], errors='coerce').fillna(0)
# 3. 基本統(tǒng)計(jì)
print("基本統(tǒng)計(jì)信息:")
print(df.describe())
# 4. 按產(chǎn)品分組統(tǒng)計(jì)
product_stats = df.groupby('產(chǎn)品').agg({
'銷量': 'sum',
'銷售額': 'sum',
'單價(jià)': 'mean'
}).sort_values('銷售額', ascending=False)
print("\n各產(chǎn)品銷售統(tǒng)計(jì):")
print(product_stats)
# 5. 時(shí)間序列分析
df.set_index('日期', inplace=True)
daily_sales = df.resample('D')['銷售額'].sum()
# 6. 可視化
plt.figure(figsize=(15, 10))
# 每日銷售額趨勢(shì)
plt.subplot(2, 2, 1)
daily_sales.plot(title='每日銷售額趨勢(shì)')
plt.ylabel('銷售額')
# 各產(chǎn)品銷量對(duì)比
plt.subplot(2, 2, 2)
product_stats['銷量'].plot(kind='bar', title='各產(chǎn)品總銷量')
plt.ylabel('銷量')
# 銷量與單價(jià)關(guān)系
plt.subplot(2, 2, 3)
sns.scatterplot(data=df, x='單價(jià)', y='銷量', hue='產(chǎn)品')
plt.title('銷量與單價(jià)關(guān)系')
plt.xlabel('單價(jià)')
plt.ylabel('銷量')
# 產(chǎn)品銷售額占比
plt.subplot(2, 2, 4)
product_stats['銷售額'].plot(kind='pie', autopct='%1.1f%%', startangle=90)
plt.title('產(chǎn)品銷售額占比')
plt.ylabel('') # 去掉默認(rèn)的ylabel
plt.tight_layout()
plt.show()八、性能優(yōu)化技巧
對(duì)于大型 Excel 文件,可以考慮以下優(yōu)化方法:
??只讀取需要的列??:
df = pd.read_excel('large_file.xlsx', usecols=['日期', '產(chǎn)品', '銷量'])分塊讀取??:
chunk_size = 10000
chunks = pd.read_excel('very_large_file.xlsx', chunksize=chunk_size)
for chunk in chunks:
process(chunk) # 處理每個(gè)數(shù)據(jù)塊??使用更高效的文件格式??:
- 將 Excel 轉(zhuǎn)換為 CSV 后處理(通常更快)
- 使用 Parquet 或 Feather 格式存儲(chǔ)中間數(shù)據(jù)
??并行處理??:
import dask.dataframe as dd
# 使用Dask處理大型數(shù)據(jù)集
ddf = dd.read_excel('large_file.xlsx')
result = ddf.groupby('產(chǎn)品').銷量.sum().compute()九、常見(jiàn)問(wèn)題解決
??中文顯示問(wèn)題??:
plt.rcParams['font.sans-serif'] = ['SimHei'] # 設(shè)置中文字體 plt.rcParams['axes.unicode_minus'] = False # 解決負(fù)號(hào)顯示問(wèn)題
??日期格式不一致??:
# 嘗試多種日期格式解析
df['日期'] = pd.to_datetime(df['日期'], errors='coerce', format='%Y-%m-%d')
df['日期'] = pd.to_datetime(df['日期'], errors='coerce', format='%d/%m/%Y')
df['日期'].fillna(pd.to_datetime('1900-01-01'), inplace=True) # 處理無(wú)法解析的日期??內(nèi)存不足錯(cuò)誤??:
- 使用
dtype參數(shù)指定列的數(shù)據(jù)類型減少內(nèi)存使用 - 分塊處理大型文件
- 使用更高效的文件格式
- 使用
十、擴(kuò)展分析方向
??預(yù)測(cè)分析??:
- 使用時(shí)間序列模型預(yù)測(cè)未來(lái)銷售額
- 應(yīng)用機(jī)器學(xué)習(xí)模型預(yù)測(cè)產(chǎn)品需求
??客戶細(xì)分??:
- 基于購(gòu)買行為進(jìn)行客戶分群
- 構(gòu)建RFM模型(最近購(gòu)買、頻率、金額)
??異常檢測(cè)??:
- 識(shí)別異常銷售記錄
- 檢測(cè)數(shù)據(jù)中的異常模式
??地理空間分析??:
- 如果數(shù)據(jù)包含地理位置信息,可以進(jìn)行地理可視化
- 分析不同地區(qū)的銷售表現(xiàn)
以上就是Python分析和處理excel文件數(shù)據(jù)的詳細(xì)步驟的詳細(xì)內(nèi)容,更多關(guān)于Python分析和處理excel數(shù)據(jù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
實(shí)操Python爬取覓知網(wǎng)素材圖片示例
大家好,本篇文章介紹的是實(shí)操Python爬取覓知網(wǎng)素材圖片示例,感興趣的朋友趕快來(lái)看一看吧,對(duì)你有用的話記得收藏起來(lái),方便下次瀏覽2021-11-11
PyCharm配置anaconda環(huán)境的步驟詳解
PyCharm是一款很好用很流行的python編輯器。Anaconda通過(guò)管理工具包、開(kāi)發(fā)環(huán)境、Python版本,大大簡(jiǎn)化了你的工作流程。今天通過(guò)本文給大家分享PyCharm配置anaconda環(huán)境,感興趣的朋友一起看看吧2020-07-07
使用TensorFlow實(shí)現(xiàn)二分類的方法示例
這篇文章主要介紹了使用TensorFlow實(shí)現(xiàn)二分類的方法示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
解決pytorch 交叉熵?fù)p失輸出為負(fù)數(shù)的問(wèn)題
這篇文章主要介紹了解決pytorch 交叉熵?fù)p失輸出為負(fù)數(shù)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
python神經(jīng)網(wǎng)絡(luò)Batch?Normalization底層原理詳解
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Batch?Normalization底層原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python通用讀取vcf文件的類(復(fù)制粘貼即可用)
這篇文章主要介紹了python通用讀取vcf文件的類(可以直接復(fù)制粘貼使用) ,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02

