什么是 pandas
pandas 是一個 Python 包,它提供了快速、靈活和豐富的數據結構,可以簡單又直觀地處理“關系”和“標簽”數據,是 Python 中做數據分析的重要模塊。詳見 pandas 官方文檔
DataFrame
pandas 有兩個非常重要的數據結構 Series 和 DataFrame。Series 是序列,多行單列,DataFrame 多行多列。先看一個圖表
圖片來自[這里](http://chrisalbon.com/python/pandas_missing_data.html)
上圖是 pandas.DataFrame 輸出樣式。最左列是索引列,默認為自增的數字序列。第一行是列名,NaN表示空,無數據。當導入數據,或者做數據框合并時,若出現空數據, pandas 會自動將此項設置為 NaN。
如何使用 pandas
我們現在有一個需求,分析電話號碼的合法性。以下例子圍繞這個展開。
導入 csv 格式文件。
import pandas as pd
df = pd.read_csv('phone.csv', encoding='utf8')
根據某列生成其他列,可如下實現。
import phonenumbers
def valid_phone_number(phones):
vphones = []
status = []
# vphone = None
for phone in phones:
try:
p=phonenumbers.parse(phone,'CN')
vphones.append(str(p.national_number))
status.append(phonenumbers.is_valid_number(p))
except Exception, e:
vphones.append(np.NaN)
status.append(np.NaN)
print e
return [vphones, status]
result = valid_phone_number(df['phone'])
df['format'] = result[0]
df['status'] = result[1]
print df
結果:
phone format status
0 +862110100000 2110100000 True
1 ?059122663000 59122663000 True
2 ? 15822203333 15822203333 True
3 0254000211111 254000211111 False
4 +862082688688 2082688688 True
5 1795111111120009 11111120009 False
6 0451811$012599 NaN NaN
在列上應用函數
def valid_phone_number(phone):
vp = None
try:
p = phonenumbers.parse(phone,'CN')
if phonenumbers.is_valid_number(p):
vp = [str(p.national_number), True]
else:
vp = [str(p.national_number), False]
except Exception, e:
print e
return vp
df['phone_status'] = df['phone'].apply(valid_phone_number)
輸出結果
phone phone_status
0 +862110100000 [2110100000, True]
1 ?059122663000 [59122663000, True]
2 ? 15822203333 [15822203333, True]
3 0254000211111 [254000211111, False]
4 +862082688688 [2082688688, True]
5 1795111111120009 [11111120009, False]
6 0451811$012599 None
拆 list 列
tags = df['phone_status'].apply(pd.Series)
tags = tags.rename(columns = lambda x : 'format' if x == 0 else 'status')
dfs = pd.concat([df['phone'], tags[:]], axis=1)
# 排序輸出
print dfs.sort_values(by='status', ascending=0)
結果:
phone format status
0 +862110100000 2110100000 True
1 ?059122663000 59122663000 True
2 ? 15822203333 15822203333 True
4 +862082688688 2082688688 True
3 0254000211111 254000211111 False
5 1795111111120009 11111120009 False
6 0451811$012599 NaN NaN
統計:
print pd.value_counts(df['status'], sort=False)
結果
False 2
True 4
Name: status, dtype: int64
輸出結果到文件 excel/csv, index=False
表示不包含索引列,即上面的最左列
# csv
df.to_csv('phones.csv', encoding='utf8', index=False)
# excel
df.to_excel('phones.xlsx', sheet_name='Sheet1', index=False)
結果如下圖:
輸出的 excel 表格
在列上應用函數修改值,去掉所有值的前后空格:
stripstr = lambda x: x.strip() if isinstance(x, unicode) else x
# 在所有列上修改
df = df.applymap(stripstr)
如果只對某列進行修改:
# 在phone列修改
df['phone'] = df['phone'].apply(stripstr)
刪除重復行
df.drop_duplicates()
刪除列
# axis=1 表示列
df.drop('phone_status', axis=1)
# 刪除索引值為1的行
df.drop(1)
空數據的處理:
# 空(NaN)值填0
df["phone"].fillna(0)
#刪除所有列都為 NaN 的行
df.dropna(how='all')
#刪除含 NaN 的行
df.dropna()
參考
10 Minutes to pandas
Data Science for Political and Social Phenomena #Python
python-phonenumbers