pandas基础学习

import pandas as pd
data1 = [1,2,3,4,5] 
s = pd.Series(data1)
s
0    1
1    2
2    3
3    4
4    5
dtype: int64
s2 = pd.Series(data1,index = ['a','b','d','g','f'])
s2
#自定义索引
a    1
b    2
d    3
g    4
f    5
dtype: int64
s2[['a','f']]    #索引
a    1
f    5
dtype: int64
#DataFrame的使用
dict = {
       'name':['张三','李四','王二','赵六'],
       'sex':['男','男','男','女'],
       'age':[18,19,20,34]
 }
df = pd.DataFrame(dict)
df
namesexage
0张三18
1李四19
2王二20
3赵六34
df.info()
#DataFrame中可以通过info函数直接查看数据类型和统计。列名后面是列的非空值统计量,以及数据类型,最后一行是DataFrame占用的内存大小,
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   name    4 non-null      object
 1   sex     4 non-null      object
 2   age     4 non-null      int64 
dtypes: int64(1), object(2)
memory usage: 224.0+ bytes
df.age.astype('str')#DataFrame的数据类型变更和numpy一样,用astype就行
0    18
1    19
2    20
3    34
Name: age, dtype: object
df['age']#DataFrame的索引方式和Series一样,它选取的是列。返回的是一组Series,索引和原DataFrame一致。
0    18
1    19
2    20
3    34
Name: age, dtype: int64
df.sex#不用中括号选取
0    男
1    男
2    男
3    女
Name: sex, dtype: object
df.loc[1] #行也可以通过通过位置获取,用索引字段loc的方式   loc是标签,iloc是所在行数字,当没有标签时候两者等价
name    李四
sex      男
age     19
Name: 1, dtype: object
df[0:2] #不需要调用ix,直接以切片的形式获取行,切片的用啊和数组一样。记住,切片无法用单独的数字选取,只能用冒号切选范围。
namesexage
0张三18
1李四19
df.age = 22 #赋值
df
namesexage
0张三22
1李四22
2王二22
3赵六22
df['age'] = [12,14,56,34]
df
namesexagecountry
0张三12China
1李四14China
2王二56China
3赵六34China
df['country'] = 'China'#当列的名称全新,在DataFrame最右边加一列
df
namesexagecountry
0张三12China
1李四14China
2王二56China
3赵六34China
df.index#索引不可更改,可通过index获得相应的信息
RangeIndex(start=0, stop=4, step=1)
df[df.age >=20]#支持常用的逻辑判断
namesexagecountry
2王二56China
3赵六34China
df[df.sex == '男']
namesexagecountry
0张三12China
1李四14China
2王二56China
df.sex == '男'
0     True
1     True
2     True
3    False
Name: sex, dtype: bool
df[(df.sex == '男')&(df.age<20)]
namesexagecountry
0张三12China
1李四14China
df[(df.sex == '女')|(df.age == 56)]
namesexagecountry
2王二56China
3赵六34China
df.query('(age == 12 and sex == "男") or(age == 34 and sex == "女") ')
#当逻辑条件复杂时,这种写法并不优雅,比如性别为男,且年龄在12岁,以及性别为女,且年龄在134岁的两类人群,
#这种过滤条件就比较复杂了。pandas中可以用query函数以类SQL语言执行查询。
#query中可以直接使用列名,它的功能远不至于此,
namesexagecountry
0张三12China
3赵六34China
posted @ 2021-06-15 23:06  visionwpc  阅读(37)  评论(0编辑  收藏  举报