- 导入 Pandas 库并简写为 pd,并输出版本号
import pandas as pd
pd.__version__
- 从列表创建 Series
import numpy as np
import pandas as pd
temp = np.arange(0, 6)
data = pd.Series(temp)
print(data)
- 从字典创建
Series
import numpy as np
import pandas as pd
temp = {'a': 1,
'b': 3}
data = pd.Series(temp)
print(data)
- 从
NumPy
数组创建 DataFrame
import numpy as np
import pandas as pd
temp = np.arange(0,6)
data = pd.DataFrame(temp, index=['a', 'b', 'c', 'd', 'e', 'f'],
columns=['temp'])
print(data)
- 从
CSV
中创建 DataFrame
,分隔符为,编码格式为gbk
df = pd.read_csv('test.csv', encoding='gbk, sep=';')
- 从字典对象
data
创建DataFrame
,设置索引为labels
import numpy as np
import pandas as pd
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
print(df)
- 显示
DataFrame
的基础信息,包括行的数量;列名;每一列值的数量、类型
print(df.info())
- 展示
df
的前3行
print(df.head(3))
- 取出
df
的animal
和age
列
print(df[['animal', 'age']])
- 取出索引为
[3, 4, 8]
行的animal
和age
列
print(df.loc[df.index[[3, 4, 8]], ['animal', 'age']])
- 取出’age’值大于3的行
print(df[df.age>3])
- 取出
age
值缺失的行
print(df[df.age.isnull()])
- 取出
age
在2,4间的行
print(df[(df.age >= 2) & (df.age <= 4)])
f
行的age
改为1.5
df.loc['f','age'] = 1.5
print(df)
- 计算
visits
的总和
print(df['visits'].sum())
- 计算每个不同种类
animal
的age
的平均数
print(df.groupby('animal')['age'].mean())
- 计算
df
中每个种类animal
的数量
print(df['animal'].value_counts())
- 先按
age
降序排列,后按visits
升序排列
df.sort_values(by=['age', 'visits'], ascending=[False, True])
print(df)
- 将
priority
列中的yes
, no
替换为布尔值True
, False
df['priority'] = df['priority'].map({'yes': True, 'no': False})
print(df)
- 将
animal
列中的snake
替换为python
df['animal'] = df['animal'].replace('snake', 'python')
print(df)
- .对每种
animal
的每种不同数量visits
,计算平均age
,即,返回一个表格,行是aniaml
种类,列是visits
数量,表格值是行动物种类列访客数量的平均年龄