参考资料 | 100-pandas-puzzles - GitHub | Pandas 百题大冲关
基本操作导入 Pandas 库并简写为 pd,并输出版本号
import pandas as pd
pd.__version__从列表创建 Seriesarr = [0, 1, 2, 3, 4]
df = pd.Series(arr) # 如果不指定索引,则默认从 0 开始
df从字典创建 Series
d = {'a':1,'b':2,'c':3,'d':4,'e':5}
df = pd.Series(d)
df从 NumPy 数组创建 DataFramedates = pd.date_range('today',periods=6) # 定义时间序列作为 index
num_arr = np.random.randn(6,4) # 传入 numpy 随机数组
columns = ['A','B','C','D'] # 将列表作为列名
df = pd.DataFrame(num_arr, index = dates, columns = columns)
df从CSV中创建 DataFrame,分隔符为“;”,编码格式为gbk
df = pd.read_csv('test.csv', encoding='gbk, sep=';')从字典对象创建DataFrame,并设置索引import numpy as np
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)
df显示df的基础信息,包括行的数量;列名;每一列值的数量、类型df.info()
# 方法二
# df.describe()展示df的前3行
df.iloc[:3]
# 方法二
#df.head(3)取出df的animal和age列df.loc[:, ['animal', 'age']]
# 方法二
# df[['animal', 'age']]取出索引为[3, 4, 8]行的animal和age列
df.loc[df.index[[3, 4, 8]], ['animal', 'age']]取出age值大于3的行df[df['age'] > 3]取出age值缺失的行
df[df['age'].isnull()]取出age在2,4间的行(不含)df[(df['age']>2)