Pandas的Series的创建
用一个列表定义一个Series
#导入库
import numpy as np
import pandas as pd
s1 = pd.Series([1, 2, 3, 4])
得到
0 1
1 2
2 3
3 4
dtype:int64
Series的属性
s1.values得到数组array([1, 2, 3, 4])
s1.index得到RangeIndex(start=0, stop=4, step=1)
直接用Numpy数组定义一个Series
#导入库
import numpy as np
import pandas as pd
s2 = pd.Series(np.arange(10))
用Python字典定义一个Series
#导入库
import numpy as np
import pandas as pd
s3 = pd.Series({'1':1, '2':2, '3':3})
得到
1 1
2 2
3 3
dtype:int64
Series的属性
s3.values得到数组array([1, 2, 3])
s3.index得到Index([‘1’, ‘2’, ‘3’], dtype=‘object’)
指定Index定义一个Series
#导入库
import numpy as np
import pandas as pd
s4 = Series([1,2,3,4], index=['A','B','C','D'])
'''
得到
A 1
B 2
C 3
D 4
dtype: int64
'''
#获取值
s4['A'] #得到1
#获取值范围
s4[s4>2]
'''
得到
C 3
D 4
dtype: int64
'''
Series转换为字典
#字典和Series可以相互转换
#导入库
import numpy as np
import pandas as pd
s4 = Series([1,2,3,4], index=['A','B','C','D'])
s4.to_dict()
Index的更改
#导入库
import numpy as np
import pandas as pd
s4 = Series([1,2,3,4], index=['A','B','C','D'])
index_1 = ['A','B','C','D','E']
s5 = pd.Series(s4, index=index_1)
'''
得到
A 1.0
B 2.0
C 3.0
D 4.0
E NaN
dtype: Float64
'''
#判断值,判断是否为空,也得到一个Series
pd.isnull(s5)
pd.notnull(s5)
给Series/Index命名
#导入库
import numpy as np
import pandas as pd
s4 = Series([1,2,3,4], index=['A','B','C','D'])
index_1 = ['A','B','C','D','E']
s5 = pd.Series(s4, index=index_1)
#给Series命名
s5.name = 'demo'
'''
得到
A 1.0
B 2.0
C 3.0
D 4.0
E NaN
Name:demo, dtype: Float64
'''
#给Index命名
s5.index.name = 'demo index'
'''
得到
demo index
A 1.0
B 2.0
C 3.0
D 4.0
E NaN
'''
Name:demo, dtype: Float64
s5.index
#得到Index(['A','B','C','D','E'], dtype='object', name = 'demo index')
Pandas的DataFrame的创建
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#导入网址的模块
import webbrowser
link = 'http://www.tiobe.com/tiobe-index'
webbrowser.open(link)
#复制粘贴方式转换成一个DataFrame
df = pd.read_clipboard()
可以得到复制内容
#检验df的属性
type(df)
得到pandas.core.frame.DataFrame
#列名
df.columns
'''
得到
Index(['May 2019', 'May 2018', 'Change', 'Programming Language', 'Ratings', 'Change.1'], dtype='object')
'''
#返回一列的值
df.Ratings
'''
得到
0 16.005%
1 14.243%
2 8.095%
3 7.830%
4 5.193%
5 3.984%
6 2.690%
7 2.555%
8 2.489%
9 1.816%
Name: Ratings, dtype: object
'''
#筛选数据
df_new = DataFrame(df, columns=['Programming Language', 'May 2018'])
'''
得到
#获取一列的方法,得到Series
df['May 2018']
'''
得到
0 1
1 2
2 3
3 4
4 6
5 5
6 8
7 9
8 7
9 13
Name: May 2018, dtype: int64
'''
#创建一个不存在的列
df_new = DataFrame(df, columns=['Programming Language', 'May 2018', 'May 2020',])
得到
#给新的columns赋值
df_new['May 2020'] = range(0,10)
df_new['May 2020'] = np.arange(0,10)同效
df_new['May 2020'] = pd.Series(np.arange(0,10))同效
得到
#单赋值某几个数值
df_new['May 2020'] = pd.Series([100, 200], index=[1,2])
得到
Pandas的Series和DataFrame
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#数据预定义
data = {
'Country': ['China', 'India', 'Brazil'],
'Capital': ['Beijing', 'New Delhi', 'Brasilia'],
'Population': ['1432732201', '1303171635', '207847528']
}
#创建Series
s1 = Series(data['Country'])
'''
得到
0 China
1 India
2 Brazil
dtype: object
'''
#创建DataFrame
df1 = DataFrame(data)
得到
#行数据
df1.iterrows()
得到
<generator object DataFrame.iterrows at 0x0000025BD9090408>
#得到每一行的元组数据
#每一行的数据类型是一个行数字和一个Series
for row in df1.iterrows():
print(row)
'''
得到
(0, Capital Beijing
Country China
Population 1432732201
Name: 0, dtype: object)
(1, Capital New Delhi
Country India
Population 1303171635
Name: 1, dtype: object)
(2, Capital Brasilia
Country Brazil
Population 207847528
Name: 2, dtype: object)
'''
#用Series创建一个DataFrame*每一个Series是一行
s1 =pd.Series(data['Capital'])
s2=pd.Series(data['Country'])
s3 =pd.Series(data['Population'])
df_new = DataFrame([s1,s2,s3])
得到
#加Index
df_new = DataFrame([s1,s2,s3], index=['Country','Capital', 'Population'])
#DataFram的转制
df_new.T
得到
Pandas的Series和DataFrame成分对比图
Dataframe IO操作
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#导入网址
import webbrowser
link = 'http://pandas.pydata.org/pandas-docs/version/0.20/io.html'
webbrowser.open(link)
df1 = pd.read_clipboard()
得到*剪切板数据提取
#剪切板的写入*可以直接用于EXCEL表格
df1.to_clipboard()
#将Dataframe导入到csv文件中,且不要Index
df1.to_csv('df1.csv', index=False)
#查看文件是否存在
!ls
#csv文件浏览
!more df1.csv
得到
#从csv文件中读取Dataframe
df2 = pd.read_csv('df1.csv')
#Dataframe转换为Json
df1.to_json()
#Json转换为Dataframe
pd.read_json(df1.to_json())
#Dataframe转换为HTML
df1.to_html('df1.html')
!ls
#Dataframe转换为EXCEL表格
df1.to_excel('df1.xlsx')
!ls
DataFrame的筛选和索引
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#查询当前目录,不必须
!pwd
#查询当前目录文件,不必须
!ls /Users/。。。
#将文件导入成为一个Dataframe
imdb = pd.read_csv('/Users/。。。/movie_metadata.csv')
#查看大小
imdb.shape
#默认返回前五行(tail返回后五行,括号加入数字可以更改行数)
imdb.head()
#返回一个选择列的Dataframe
imdb[['color','director_name']]
得到(共5000多行,只截图省略版,在显示不开是会显示Dataframe的容量)
5043 rows × 2 columns
#筛选后看前几行
sub_df = imdb[['director_name', 'movie_title','imdb_score']]
sub_df.head(5)
得到
#切片第几行到第几行(10-20),第几列到第几列(0-2)
tmp_df = sub_df.iloc[10:20,0:2]
得到
#切片的再切片(只切片行)
tmp_df.iloc[2:4,:]
得到
#显示列显示不开也会,同时显示Dataframe的容量
imdb.head()
得到
5 rows × 28 columns
#切片索引,筛选制定列,loc返回的是索引不是行列数
tmp_df.loc[15:17,:'director_name']
得到
Series and DataFrame的索引更改
shift+TAB得到函数介绍
Series的索引更改
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#新的Series
s1 = Series([1,2,3,4], index=['A','B','C','D'])
#Series的索引更改
s1.reindex(index=['A','B','C','D','E'])
'''
得到
A 1.0
B 2.0
C 3.0
D 4.0
E NaN
dtype: float64
'''
#Series的索引更改,将所有的空值填满
s1.reindex(index=['A','B','C','D','E'], fill_value=10)
#新的Series
s2 = Series(['A','B','C'], index=[1,5,10])
#Series的索引更改,按照顺序将不存在的标签填充'ffill'方法是按照之前的空余赋值
s2.reindex(index=range(15),method='ffill')
#Series的索引更改,也可以减少
s1.reindex(index=['A','B'])
'''
得到
A 1
B 2
dtype: int64
'''
#Series的drop,去掉指定的索引
s1.drop('A')
'''
得到
B 2
C 3
D 4
dtype: int64
'''
DataFrame的索引更改
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#新的DataFrame,内容为25位随机数的
*random.rand是随机数,random.randn是正态分布随机数
df1 = DataFrame(np.random.rand(25).reshape([5,5]), index=['A','B','D','E','F'], columns=['c1','c2','c3','c4','c5'])
#DataFrame的索引更改,增加一行
df1.reindex(index=['A','B','C','D','E','F'])
#DataFrame的索引更改,增加一列
df1.reindex(columns=['c1','c2','c3','c4','c5','c6'])
#DataFrame的索引更改,行列均有增加
df1.reindex(index=['A','B','C','D','E','F'],columns=['c1','c2','c3','c4','c5','c6'])
得到
#DataFrame的索引更改,也可以减少
df1.reindex(index=['A','B'])
得到
#DataFrame的drop,去掉指定的索引axis=0代表一行,axis=1代表一列
df1.drop('c1', axis=1)
得到
NaN介绍
NaN的意思是,不是一个数字
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#创建一个为NaN的数据类型
n = np.nan
type(n) #类型是float
m = 1
m + n #结果还是NaN
Series的NaN
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
s1 = Series([1, 2, np.nan, 3, 4], index=['A','B','C','D','E'])
'''
得到
A 1.0
B 2.0
C NaN
D 3.0
E 4.0
dtype: float64
'''
#是否为NaN返回一个Series
s1.isnull()
'''
得到
A False
B False
C True
D False
E False
dtype: bool
'''
#是否不是NaN返回一个Series
s1.notnull()
'''
得到
A True
B True
C False
D True
E True
dtype: bool
'''
#把数字是NaN的去掉
s1.dropna()
'''
得到
A 1.0
B 2.0
D 3.0
E 4.0
dtype: float64
'''
DataFrame的NaN
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
dframe = DataFrame([[1,2,3],[np.nan,5,6],[7,np.nan,9],[np.nan,np.nan,np.nan]])
得到
#是否为NaN返回一个DataFrame
dframe.isnull()
得到
#是否不是NaN返回一个DataFrame
dframe.notnull()
得到
#axis=0对行操作,axis=1对列操作,how如何操作,any只要有就去掉,all全是才操作
df1 = dframe.dropna(axis=0,how='all')
得到
#创建新的DataFrame
dframe2 = DataFrame([[1,2,3,np.nan],[2,np.nan,5,6],[np.nan,7,np.nan,9],[1,np.nan,np.nan,np.nan]])
得到
#dframe.dropna(thresh=2),即把NaN数量大于2的行和列删掉
df2 = dframe2.dropna(thresh=2)
得到
#还可以写为dframe.dropna(thresh=None)默认,即把有NaN的所有行和列都删掉
dframe.dropna()
得到
#将DataFrame里有NaN的位置更改数字,0列为0,1列为1。。。
dframe2.fillna(value={0:0,1:1,2:2,3:3})
得到
#即将DataFrame里有NaN的位置更改为1
dframe.fillna(1)
得到
多级Index
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#创建新的Series,两级的Index
s1 = Series(np.random.randn(6), index=[['1','1','1','2','2','2'],['a','b','c','a','b','c']])
'''
得到
1 a -0.442965
b -0.854952
c -0.861487
2 a 0.298808
b 0.421709
c 0.381531
dtype: float64
'''
#两级Index的数据类型
type(s1['1'])
'''
得到
pandas.core.series.Series
'''
#返回对应两级Index的数值
s1['1']['a']
'''
得到
-0.44296507622393816
'''
#返回对应二级Index的数值,任意一级Index
s1[:,'a']
'''
得到
1 -0.442965
2 0.298808
dtype: float64
'''
#可以将两级Index的Series转换为DataFrame
df1 = s1.unstack()
得到
#可以将两级Index的Series的二级Index数值转换为DataFrame
df2 = DataFrame([s1['1'],s1['2']])
得到
#可以将DataFrame转换为两级Index的Series
s2 = df1.unstack()
'''
得到
a 1 -0.442965
2 0.298808
b 1 -0.854952
2 0.421709
c 1 -0.861487
2 0.381531
dtype: float64
'''
#可以将DataFrame转换为两级Index的Series,转置转成Series(一二级反转)
s2 = df1.T.unstack()
'''
得到
1 a -0.442965
b -0.854952
c -0.861487
2 a 0.298808
b 0.421709
c 0.381531
dtype: float64
'''
#创建新的DataFrame,有两级Index,对应定义columns
df = DataFrame(np.arange(16).reshape(4,4), index=[['a','a','b','b'],[1,2,1,2]],
columns=[['BJ','BJ','SH','GZ'],[8,9,8,8]])
得到
#访问元素,可能得到Series,也可能得到DataFrame(df['BJ'])
df['BJ'][8]
'''
得到
a 1 0
2 4
b 1 8
2 12
Name: 8, dtype: int64
'''
DataFrame的Mapping
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#创建新的DataFrame,以字典方式创建
df1 = DataFrame({"城市":["北京","上海","广州"], "人口":[1000,2000,1500]}, index=['A','B','C'])
得到
#增加一列
df1['GDP'] = Series([1000,2000,1500], index=['A','B','C'])
得到
#创建一个字典
gdp_map = {'北京':1000, '上海':2000, '广州':1500}
#增加一列的Mapping方法
df1['GDP'] = df1['城市'].map(gdp_map)
与以上方法等效,但Series方法必须制定index
得到
Series的Replace
#导入库
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
#创建新的Series
s1 = Series(np.arange(10))
'''
得到
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
dtype: int64
'''
#Replace方法,[index][更改的数值]
s1.replace([1,2,3], [10,20,30])
'''
得到
0 0
1 10
2 20
3 30
4 4
5 5
6 6
7 7
8 8
9 9
dtype: int64
'''