创建一个DataFrame,它有几种创建方式:列表,序列(pandas.Series), numpy.ndarray的字典
二维numpy.ndarray
别的DataFrame
结构化的记录(structured arrays)
其中,我最喜欢的是通过二维ndarray创建DataFrame,因为代码敲得最少:- import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(3, 4))df0 1 2 30 0.236175 -0.394792 -0.171866 0.3040121 0.651926 0.989046 0.160389 0.4829362 -1.039824 0.401105 -0.492714 -1.220438
复制代码 当然你还可以参考我的这篇文章从mysql数据库或者csv文件中载入数据到dataframe。
dataframe中index用来标识行,column标识列,shape表示维度。- df.indexdf.columnsdf.shape
复制代码 通过describe方法,我们可以对df中的数据有个大概的了解:- df.describe()0 1 2 3count 3.000000 3.000000 3.000000 3.000000mean -0.050574 0.331786 -0.168064 -0.144496std 0.881574 0.694518 0.326568 0.936077min -1.039824 -0.394792 -0.492714 -1.22043825% -0.401824 0.003156 -0.332290 -0.45821350% 0.236175 0.401105 -0.171866 0.30401275% 0.444051 0.695076 -0.005739 0.393474max 0.651926 0.989046 0.160389 0.482936
复制代码 数据select, del, update。[h1]按照列名select:[/h1]- df[0] 0 0.2361751 0.6519262 -1.039824
复制代码 [h1]按照行数select:[/h1]- df.loc[0] 0 0.2361751 -0.3947922 -0.1718663 0.304012
复制代码 [h1]按照行数和列数select:[/h1]- df.iloc[3] #选取第3行df.iloc[2:4] #选取第2到第3行df.iloc[0,1] #选取第0行1列的元素dat.iloc[:2, :3] #选取第0行到第1行,第0列到第2列区域内的元素df1.iloc[[1,3,5],[1,3]] #选取第1,3,5行,第1,3列区域内的元素
复制代码 [h1]删除某列:[/h1]- del df[0]df1 2 30 -0.394792 -0.171866 0.3040121 0.989046 0.160389 0.4829362 0.401105 -0.492714 -1.220438
复制代码 [h1]删除某行:[/h1]- df.drop(0) 1 2 31 0.989046 0.160389 0.4829362 0.401105 -0.492714 -1.220438
复制代码 [h1]运算。[/h1]基本运算:- df[4] = df[1] + df[2] 1 2 3 40 -0.394792 -0.171866 0.304012 -0.5666591 0.989046 0.160389 0.482936 1.1494352 0.401105 -0.492714 -1.220438 -0.091609
复制代码 map运算,和python中的map有些类似:[h1]apply运算:[/h1]- df.apply(sum) 1 0.9953592 -0.5041923 -0.4334894 0.491167
复制代码 [h1]Group by 操作。[/h1]pandas中的group by 操作是我的最爱,不用把数据导入excel或者mysql就可以进行灵活的group by 操作,简化了分析过程。- df[0] = ['A', 'A', 'B']df 1 2 3 4 00 -0.394792 -0.171866 0.304012 -0.566659 A1 0.989046 0.160389 0.482936 1.149435 A2 0.401105 -0.492714 -1.220438 -0.091609 B g = df.groupby([0]) g.size() A 2B 1 g.sum() 1 2 3 40A 0.594254 -0.011478 0.786948 0.582776B 0.401105 -0.492714 -1.220438 -0.091609
复制代码- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- groupby选择列和迭代g = df.groupby(df['artist_id'])gsize=g.size()aa=g.sum()
复制代码 [h1]导出到csv文件[/h1]dataframe可以使用to_csv方法方便地导出到csv文件中,如果数据中含有中文,一般encoding指定为”utf-8″,否则导出时程序会因为不能识别相应的字符串而抛出异常,index指定为False表示不用导出dataframe的index数据。- df.to_csv(file_path, encoding='utf-8', index=False)
复制代码 |
|