读取大文件(内存有限):
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')
# 确保理解你的数据