一、pandas中series用法
(1)series创建
#带标签的数组
# 直接创建
t2 = pd.Series([1,5,4,98,5], index=list('abcde'))# 带标签的数组,不加index则默认标签从0开始
# 通过字典创建
temp_dict = {
"name":"xiaohong", "age":30, "Tel":10086}
t3 = pd.Series(temp_dict)
(2)引用
t3[[1,2]] # 取第二个到第三个
t3[1:] # 同上的另一种取法
t2[t2>1] # 取出元素中大于一的数和其标签
(3)index索引
for i in t3.index: # 使用index(索引)便利
print(i)
list(t3.index) # 使用list对索引转换成列表
(4)values
t3.values # 是ndarray类型,可遍历、切片和索引
array(['xiaohong', 30, 10086], dtype=object) # 上面的结果
二、pandas读取数据
df = pd.read_csv(r"*****")
print(df) # 示例如下,数据前有标签(标题无)
Row_Labels Count_AnimalName
0 1 1
1 2 2
2 40804 1
3 90201 1
三、pandas里面dataframe类型
(1)sort 排序的用法
df = df.sort_values(by="Count_AnimalName", ascending=False) # 排序
print(df.head(5)) # 取前五行
(2)切片和索引
# Pandas 的切片和索引
print(df[:20]) # 取前20个,方括号写数字表示行操作,写字符串表示对列操作
print('********************8')
print(df[:20]["Row_Labels"]) # 这个只有一列,为series类型
t3 = pd.DataFrame(np.arange(12).reshape(3, 4), index=list("abc"), columns=list("wxyz"))
print(t3)
(3)loc用标签索引
t00 = t3.loc[["a", "c"], ["x", "z"]] # 这个loc标签索引(取行不用打列,取列行要打上:)能选中最后一个
print(t00)
# iloc用法和切片差不多,多了[]而已
t01 = t3.iloc[[0, 2], [2, 1]] # 2,1 没问题,见结果
print(t01)
print("******************")
t3.iloc[1:, :2] = np.nan # 没问题,dataframe自动转化为float类型
print(t3)
(4)布尔索引和nan的处理
# 布尔索引
print(df[(800<df['Count_AnimalName'])&(df['Count_AnimalName']<1000)])
# NaN的处理。1、判断有无NaN
print(pd.isnull(t3)) # isnull函数判断
print(pd.notnull(t3))
print(t3[pd.notnull(t3["w"])]) # 显示了a这一行,因为a,w不为null
# t3.dropna(axis=0, how='all', inplace=True) # 删除全为all的一行,然后替换
t02 = t3.fillna(t3.mean()) # 用均值填充nan
print(t02)
t3["w"] = t3["w"].fillna(t3['w'].mean()) # 具体修改填充某一列
# pandas算均值会自动不包括nan这一行,这样处理会方便很多,nan直接空出来就好,不要填充字段
四、电影数据实例
(1)直方图统计running time
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib import font_manager
data_movies = r"C:\Users\dell\Desktop\Python学习\14100_HM数据科学库课件\day04\datasets_IMDB-Movie-Data.csv"
df = pd.read_csv(data_movies)
print(df.head(1))
print(df.info())
# creating.runtime的分布情况
# 选择图形,直方图
# 准备数据
runtime_data = df["Runtime (Minutes)"].values
runtime_max = runtime_data.max()
runtime_min = runtime_data.min()
# 计算组数
num_bin = (runtime_max - runtime_min)//5
my_font = font_manager.FontProperties(fname=r"G:\Python_Learning\untitled\test\simsun.ttc") # 调取中文字体
plt.figure(figsize=(20, 8), dpi=80) # 调图表大小
plt.hist(runtime_data, num_bin)
plt.xticks(range(runtime_min, runtime_max + 5, 5))
plt.grid(True, linestyle="-.", alpha=0.5) # 显示网络,透明度为0.5
plt.show()
(2)获取某一列不重复的数据数
import pandas as pd
data_movies = r"C:\Users\dell\Desktop\Python学习\14100_HM数据科学库课件\day04\datasets_IMDB-Movie-Data.csv"
df = pd.read_csv(data_movies)
# print(df.head(1))
# 获取电影的平均评分
print(df['Rating'].mean())
# 导演人数
print(len(set(df["Director"].tolist()))) # 转化为列表,set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等
print(len(df["Director"].unique())) # unique表示唯一
# 获取演员人数
temp_actors_list = df["Actors"].str.split(",").tolist()
# print(temp_actors_list)
actors_list = [i for j in temp_actors_list for i in j]
# print(actors_list)
actors_num = len(set(actors_list))
print(actors_num)