讀取大文件(內存有限):
import pandas as pd reader = pd.read_csv("tap_fun_test.csv", sep=',', iterator=True) loop = True chunkSize = 100000 chunks = [] while loop: try: chunk = reader.get_chunk(chunkSize) chunks.append(chunk) except StopIteration: loop = False print("Iteration is stopped.") df = pd.concat(chunks, ignore_index=True) print(df.shape)
有時會有與列數不對應的行,因此會報錯加上error_bad_lines=False即可。
導入和保存數據:
讀取最常見的csv和excel文件。
1
|
pip install xlrd xlwt openpyxl
|
pd.read_csv(filepath_or_buffer, sep=',', delimiter=None, header='infer') # header = None
pd.read_excel('foo.xlsx', 'Sheet1',header=0) # header = None
讀取mysql數據庫,在實際工作環境中最為常用.
import pandas as pd import pymysql conn = pymysql.connect(host='127.0.0.1', \ user='root',password='123456', \ db='TESTDB',charset='utf8', \ use_unicode=True) sql = 'select GroupName from group limit 20' df = pd.read_sql(sql, con=conn) print(df.head()) df.to_csv("data.csv") conn.close()
df.to_csv("name.csv",header=True,index=True)
df.to_excel(excel_writer, sheet_name='Sheet1', header=True, index=True)
創建對象DataFrame,Series
DataFrame 表(表也可以是一列,多了columns名), Series 一維(行或列)
pd.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)
pd.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
pd.Series(np.array([
1
,
2
,
3
,
4
]),index
=
[
'a'
,
'b'
,
'c'
,
'd'
])
>>>a
1
b
2
c
3
d
4
dtype: int32
a1
=
np.array([
1
,
2
,
3
])
a2
=
np.array([
4
,
5
,
6
])
pd.DataFrame([a1,a2],index
=
[
1
,
2
],columns
=
[
"a"
,
"b"
,
"c"
])
# 第一個參數為矩陣
>>>
a b c
1
1
2
3
2
4
5
6
|
查看數據:
df.head() df.tail()
df.index # 行索引
df.columns
df.values # 返回ndarry結構,重點
df.dtypes
df.count() # 計算每列的個數,尋找缺失值
df.T # 轉置
df.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, by=None)
df.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last') # 比較有用
df.rename() # 修改列名
切片和索引:
1
2
3
4
5
6
7
8
9
|
df[
'A'
]
# 索引列
df.loc[:,
"A"
:
"C"
]
# 通過標簽來選擇
df.iloc[:,
2
:]
# 通過位置來選擇
df[df>
0
]
# 通過布爾索引來選擇數據
df.isin(values)
# 返回布爾類型
|
設置:
df.index = ndarray
df.columns = ndarray
df.iloc[:,0] = ndarray
df.loc[0,:] = ndarray
拼接:
pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True)
參數說明
objs: series,dataframe或者是panel構成的序列lsit
axis: 需要合並鏈接的軸,0是行,1是列
join:連接的方式 inner,或者outer
其他一些參數不常用,用的時候再補上說明。
拼接完了之后需要df.sort_index 或者df.sort_values 進行排序。
缺失值處理:
df.drop() # 刪除行(axis=0)、列(axis=1)
df.dropna(how="any") # 'any':如果存在任何NA值,則刪除該行或列。'all':如果所有值都是NA,則刪除該行或列。
df.fillna()
pd.isnull(df) # 返回布爾類型
統計:
# group by groupby之后的數據並不是DataFrame格式的數據,而是特殊的groupby類型,size()后返回Series結果。
df.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)
# 數據透視表
pd.pivot_table(data, values=None, index=None, columns=None, aggfunc='mean', fill_value=None, margins=False, dropna=True, margins_name='All')
# 確保理解你的數據