在數(shù)據(jù)驅(qū)動(dòng)的時(shí)代,有效的數(shù)據(jù)治理是企業(yè)挖掘數(shù)據(jù)價(jià)值、驅(qū)動(dòng)科學(xué)決策的基石。數(shù)據(jù)分析與清洗作為數(shù)據(jù)治理流程中的核心環(huán)節(jié),直接決定了后續(xù)分析與建模的質(zhì)量。本文將聚焦于強(qiáng)大的Python數(shù)據(jù)分析庫(kù)pandas,探討如何高效地進(jìn)行數(shù)據(jù)清洗、分析,并重點(diǎn)介紹創(chuàng)建新字段的實(shí)用技巧。為助力讀者實(shí)踐,文末將提供同款示例數(shù)據(jù)供下載練習(xí)。
pandas是基于NumPy構(gòu)建的、專為結(jié)構(gòu)化數(shù)據(jù)(如表格數(shù)據(jù))設(shè)計(jì)的庫(kù)。它提供了兩種核心數(shù)據(jù)結(jié)構(gòu):Series(一維數(shù)組)和DataFrame(二維表格)。憑借其簡(jiǎn)潔的API和強(qiáng)大的功能,pandas已成為數(shù)據(jù)科學(xué)家和數(shù)據(jù)分析師進(jìn)行數(shù)據(jù)預(yù)處理和探索性分析(EDA)的首選工具。其核心優(yōu)勢(shì)在于能輕松處理數(shù)據(jù)加載、清洗、轉(zhuǎn)換、合并、重塑以及分析等一系列任務(wù)。
在利用pandas處理數(shù)據(jù)時(shí),通常遵循以下關(guān)鍵步驟:
pd.read<em>csv()、pd.read</em>excel()等函數(shù)將數(shù)據(jù)加載為DataFrame。隨后通過(guò).head()、.info()、.describe()方法快速了解數(shù)據(jù)規(guī)模、列類型、缺失值和統(tǒng)計(jì)摘要。.isnull()或.isna()。.dropna()刪除含有缺失值的行或列。.fillna()用特定值(如均值、中位數(shù)、眾數(shù)或前向/后向填充)進(jìn)行填充。.duplicated()識(shí)別重復(fù)行,并用.drop_duplicates()刪除,確保數(shù)據(jù)唯一性。.astype()轉(zhuǎn)換列的數(shù)據(jù)類型(如將字符串轉(zhuǎn)為日期)。對(duì)于分類數(shù)據(jù)或文本數(shù)據(jù),可能需要進(jìn)行標(biāo)準(zhǔn)化(如大小寫統(tǒng)一)或編碼(如獨(dú)熱編碼)。創(chuàng)建新字段(派生列)是數(shù)據(jù)分析中從現(xiàn)有數(shù)據(jù)提煉新信息的關(guān)鍵操作。pandas提供了極其靈活的方式來(lái)實(shí)現(xiàn)。
直接對(duì)列進(jìn)行數(shù)學(xué)運(yùn)算來(lái)創(chuàng)建新列。`python
import pandas as pd
# 假設(shè)df中有‘單價(jià)’和‘?dāng)?shù)量’列
df['總金額'] = df['單價(jià)'] * df['數(shù)量']`
apply()函數(shù)應(yīng)用自定義邏輯當(dāng)創(chuàng)建邏輯較為復(fù)雜時(shí),apply()函數(shù)非常強(qiáng)大,它可以將一個(gè)函數(shù)應(yīng)用到DataFrame的每一行或每一列。`python
# 示例:根據(jù)成績(jī)創(chuàng)建等級(jí)列
def get_grade(score):
if score >= 90:
return 'A'
elif score >= 80:
return 'B'
else:
return 'C'
df['等級(jí)'] = df['成績(jī)'].apply(get_grade)`
assign()方法進(jìn)行鏈?zhǔn)讲僮?/h4>
assign()方法可以方便地在不修改原DataFrame的情況下創(chuàng)建新列,并支持鏈?zhǔn)秸{(diào)用,使代碼更清晰。`python
df = df.assign(
折扣后金額 = lambda x: x['總金額'] * 0.9,
是否大單 = lambda x: x['折扣后金額'] > 1000
)`
np.where()或.mask()/.where()np.where()函數(shù)是進(jìn)行元素級(jí)條件賦值的利器。`python
import numpy as np
df['客戶類型'] = np.where(df['消費(fèi)金額'] > 1000, 'VIP', '普通')`
對(duì)于字符串類型的列,可以通過(guò).str訪問(wèn)器使用豐富的字符串方法。`python
# 假設(shè)‘姓名’列,提取姓氏(假設(shè)為第一個(gè)字符)
df['姓氏'] = df['姓名'].str[0]
# 分割地址信息
df['城市'] = df['地址'].str.split('市').str[0]`
如果數(shù)據(jù)包含日期時(shí)間列,可以通過(guò).dt訪問(wèn)器提取豐富信息。`python
df['訂單年份'] = df['訂單日期'].dt.year
df['訂單月份'] = df['訂單日期'].dt.month
df['星期幾'] = df['訂單日期'].dt.day_name()`
為了幫助您將上述理論付諸實(shí)踐,我們準(zhǔn)備了一份模擬的電商訂單數(shù)據(jù)集(sample<em>sales</em>data.csv),其中包含:order<em>id(訂單ID)、customer</em>id(客戶ID)、product(產(chǎn)品)、quantity(數(shù)量)、unit<em>price(單價(jià))、order</em>date(訂單日期)等字段。
您的數(shù)據(jù)分析與處理任務(wù)如下:
1. 加載數(shù)據(jù),并檢查數(shù)據(jù)概覽與缺失值。
2. 計(jì)算每個(gè)訂單的total<em>amount(總金額 = 數(shù)量 * 單價(jià))。
3. 基于total</em>amount,創(chuàng)建一個(gè)新列order<em>size,規(guī)則為:總金額>500為“大單”,100-500之間為“中單”,小于100為“小單”。
4. 從order</em>date中提取order<em>year和order</em>quarter(季度)字段。
5. 計(jì)算每個(gè)客戶的總消費(fèi)金額,并創(chuàng)建新列customer_type,總消費(fèi)>2000的標(biāo)記為“高價(jià)值客戶”。
示例代碼框架:`python
import pandas as pd
import numpy as np
df = pd.readcsv('samplesalesdata.csv', parsedates=['order_date'])
print(df.info())
print(df.head())
df['totalamount'] = df['quantity'] * df['unitprice']
conditions = [
df['totalamount'] > 500,
(df['totalamount'] >= 100) & (df['totalamount'] <= 500),
df['totalamount'] < 100
]
choices = ['大單', '中單', '小單']
df['order_size'] = np.select(conditions, choices, default='未知')
df['orderyear'] = df['orderdate'].dt.year
df['orderquarter'] = df['orderdate'].dt.quarter
customertotal = df.groupby('customerid')['totalamount'].sum().resetindex()
customertotal.rename(columns={'totalamount': 'customerlifetimevalue'}, inplace=True)
df = pd.merge(df, customertotal, on='customerid', how='left')
df['customertype'] = np.where(df['customerlifetime_value'] > 2000, '高價(jià)值客戶', '一般客戶')
print(df[['orderid', 'customerid', 'totalamount', 'ordersize', 'orderyear', 'customertype']].head())`
###
通過(guò)pandas進(jìn)行數(shù)據(jù)清洗、分析與字段創(chuàng)建,是一個(gè)將原始數(shù)據(jù)轉(zhuǎn)化為高價(jià)值信息流的系統(tǒng)過(guò)程。掌握這些技能,不僅能提升數(shù)據(jù)治理的效率與質(zhì)量,更能為深度分析和機(jī)器學(xué)習(xí)模型構(gòu)建打下堅(jiān)實(shí)的基礎(chǔ)。建議讀者下載提供的示例數(shù)據(jù),親自動(dòng)手運(yùn)行和修改上述代碼,在實(shí)踐中深化理解,從而在面對(duì)真實(shí)、復(fù)雜的數(shù)據(jù)挑戰(zhàn)時(shí)游刃有余。
(注:示例數(shù)據(jù)文件可通過(guò)提供的鏈接或附件下載。)
如若轉(zhuǎn)載,請(qǐng)注明出處:http://www.cooid.cn/product/74.html
更新時(shí)間:2026-02-14 06:27:44