Python Dataframe遍历,删除,初始化操作

创建一个DataFrame,它有几种创建方式:

列表,序列(pandas.Series), numpy.ndarray的字典
二维numpy.ndarray
别的DataFrame
结构化的记录(structured arrays)
其中,我最喜欢的是通过二维ndarray创建DataFrame,因为代码敲得最少:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(3, 4))
df
0 1 2 3
0 0.236175 -0.394792 -0.171866 0.304012
1 0.651926 0.989046 0.160389 0.482936
2 -1.039824 0.401105 -0.492714 -1.220438

当然你还可以参考我的这篇文章从mysql数据库或者csv文件中载入数据到dataframe。
dataframe中index用来标识行,column标识列,shape表示维度。

df.index
df.columns
df.shape

通过describe方法,我们可以对df中的数据有个大概的了解:

df.describe()
0 1 2 3
count 3.000000 3.000000 3.000000 3.000000
mean -0.050574 0.331786 -0.168064 -0.144496
std 0.881574 0.694518 0.326568 0.936077
min -1.039824 -0.394792 -0.492714 -1.220438
25% -0.401824 0.003156 -0.332290 -0.458213
50% 0.236175 0.401105 -0.171866 0.304012
75% 0.444051 0.695076 -0.005739 0.393474
max 0.651926 0.989046 0.160389 0.482936

数据select, del, update。

按照列名select:


df[0]
 
0 0.236175
1 0.651926
2 -1.039824

按照行数select:

df[:3] #选取前3行
按照索引select:
df.loc[0]
 
0 0.236175
1 -0.394792
2 -0.171866
3 0.304012

按照行数和列数select:

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列区域内的元素

删除某列:

del df[0]
df
1 2 3
0 -0.394792 -0.171866 0.304012
1 0.989046 0.160389 0.482936
2 0.401105 -0.492714 -1.220438

删除某行:

df.drop(0)
 
1 2 3
1 0.989046 0.160389 0.482936
2 0.401105 -0.492714 -1.220438

运算。

基本运算:

df[4] = df[1] + df[2]
 
1 2 3 4
0 -0.394792 -0.171866 0.304012 -0.566659
1 0.989046 0.160389 0.482936 1.149435
2 0.401105 -0.492714 -1.220438 -0.091609

map运算,和python中的map有些类似:

df[4].map(int)
0 0
1 1
2 0

apply运算:

df.apply(sum)
 
1 0.995359
2 -0.504192
3 -0.433489
4 0.491167

Group by 操作。

pandas中的group by 操作是我的最爱,不用把数据导入excel或者mysql就可以进行灵活的group by 操作,简化了分析过程。

df[0] = ['A', 'A', 'B']
df
 
1 2 3 4 0
0 -0.394792 -0.171866 0.304012 -0.566659 A
1 0.989046 0.160389 0.482936 1.149435 A
2 0.401105 -0.492714 -1.220438 -0.091609 B
 
g = df.groupby([0])
 
g.size()
 
A 2
B 1
 
g.sum()
 
1 2 3 4
0
A 0.594254 -0.011478 0.786948 0.582776
B 0.401105 -0.492714 -1.220438 -0.091609
groupby选择列和迭代
g = df.groupby(df['artist_id'])
gsize=g.size()
aa=g.sum()

导出到csv文件

dataframe可以使用to_csv方法方便地导出到csv文件中,如果数据中含有中文,一般encoding指定为”utf-8″,否则导出时程序会因为不能识别相应的字符串而抛出异常,index指定为False表示不用导出dataframe的index数据。

df.to_csv(file_path, encoding='utf-8', index=False)

作者:Deep_IT
来源:CSDN
原文:https://blog.csdn.net/wang4959520/article/details/51087957
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/u011095110/article/details/83620436
今日推荐