movie_data2.xlsx

酒店数据1.xlsx

首先:读入我们上节课保存的数据文件movie_data.xlsx

import pandas as pd
import numpy as np
df = pd.read_excel(r"C:\\Users\\Lovetianyi\\Desktop\\python\\作业3\\movie_data.xlsx",index_col = 0)
df[:5]

无标题

2.1 数据格式转换

在做数据分析的时候,原始数据往往会因为各种各样的原因产生各种数据格式的问题。 数据格式是我们非常需要注意的一点,数据格式错误往往会造成很严重的后果。 并且,很多异常值也是我们经过格式转换后才会发现,对我们规整数据,清洗数据有着重要的作用。

查看格式

df["投票人数"].dtype

dtype(‘int64’)

df["投票人数"] = df["投票人数"].astype("int") #转换格式
df[:5]

无标题

df["产地"].dtype

dtype(‘0’)

df["产地"] = df["产地"].astype("str")

将年份转化为整数格式

df["年代"] = df["年代"].astype("int") #有异常值会报错

---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)
<ipython-input-9-aafea50a8773> in <module>
----> 1df["年代"]= df["年代"].astype("int")#有异常值会报错~\\anaconda3\\lib\\site-packages\\pandas\\core\\generic.py in astype(self, dtype, copy, errors)   5696else:   5697# else, only a single dtype is given-> 5698new_data= self._data.astype(dtype=dtype, copy=copy, errors=errors)   5699return self._constructor(new_data).__finalize__(self)   5700

~\\anaconda3\\lib\\site-packages\\pandas\\core\\internals\\managers.py in astype(self, dtype, copy, errors)    580
    581def astype(self, dtype, copy: bool=False, errors: str="raise"):--> 582return self.apply("astype", dtype=dtype, copy=copy, errors=errors)    583
    584def convert(self,**kwargs):~\\anaconda3\\lib\\site-packages\\pandas\\core\\internals\\managers.py in apply(self, f, filter, **kwargs)    440                 applied= b.apply(f,**kwargs)    441else:--> 442applied= getattr(b, f)(**kwargs)    443             result_blocks= _extend_blocks(applied, result_blocks)    444

~\\anaconda3\\lib\\site-packages\\pandas\\core\\internals\\blocks.py in astype(self, dtype, copy, errors)    623             vals1d= values.ravel()    624try:--> 625values= astype_nansafe(vals1d, dtype, copy=True)    626except(ValueError, TypeError):    627# e.g. astype_nansafe can fail on object-dtype of strings~\\anaconda3\\lib\\site-packages\\pandas\\core\\dtypes\\cast.py in astype_nansafe(arr, dtype, copy, skipna)    872# work around NumPy brokenness, #1987    873if np.issubdtype(dtype.type, np.integer):--> 874return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)    875
    876# if we have a datetime/timedelta array of objectspandas\\_libs\\lib.pyx in pandas._libs.lib.astype_intsafe()ValueError: invalid literal for int() with base 10: '2008\\u200e'
df[df.年代 == "2008\\u200e"] #找到异常数据

Untitled

df[df.年代 == "2008\\u200e"]["年代"].values 
#后面是unicode的控制字符,使得其显示靠左,因此需要处理删除

array(['2008\\u200e'], dtype=object)

df.loc[[14934,15205],"年代"] = 2008
df.loc[14934]
名字                    奶奶强盗团
投票人数                  12591
类型                 剧情/喜剧/动作
产地                       韩国
上映时间    2010-03-18 00:00:00
时长                      107
年代                     2008
评分                      7.7
首映地点                     韩国
Name: 14934, dtype: object
df["年代"] = df["年代"].astype("int")
df["年代"][:5]

0 1994 1 1957 2 1997 3 1994 4 1993 Name: 年代, dtype: int32

将时长转化为整数格式

df["时长"] = df["时长"].astype("int")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-97b0e6bbe2ae> in <module>
----> 1 df["时长"] = df["时长"].astype("int")

~\\anaconda3\\lib\\site-packages\\pandas\\core\\generic.py in astype(self, dtype, copy, errors)
   5696         else:
   5697             # else, only a single dtype is given
-> 5698             new_data = self._data.astype(dtype=dtype, copy=copy, errors=errors)
   5699             return self._constructor(new_data).__finalize__(self)
   5700 

~\\anaconda3\\lib\\site-packages\\pandas\\core\\internals\\managers.py in astype(self, dtype, copy, errors)
    580 
    581     def astype(self, dtype, copy: bool = False, errors: str = "raise"):
--> 582         return self.apply("astype", dtype=dtype, copy=copy, errors=errors)
    583 
    584     def convert(self, **kwargs):

~\\anaconda3\\lib\\site-packages\\pandas\\core\\internals\\managers.py in apply(self, f, filter, **kwargs)
    440                 applied = b.apply(f, **kwargs)
    441             else:
--> 442                 applied = getattr(b, f)(**kwargs)
    443             result_blocks = _extend_blocks(applied, result_blocks)
    444 

~\\anaconda3\\lib\\site-packages\\pandas\\core\\internals\\blocks.py in astype(self, dtype, copy, errors)
    623             vals1d = values.ravel()
    624             try:
--> 625                 values = astype_nansafe(vals1d, dtype, copy=True)
    626             except (ValueError, TypeError):
    627                 # e.g. astype_nansafe can fail on object-dtype of strings

~\\anaconda3\\lib\\site-packages\\pandas\\core\\dtypes\\cast.py in astype_nansafe(arr, dtype, copy, skipna)
    872         # work around NumPy brokenness, #1987
    873         if np.issubdtype(dtype.type, np.integer):
--> 874             return lib.astype_intsafe(arr.ravel(), dtype).reshape(arr.shape)
    875 
    876         # if we have a datetime/timedelta array of objects

pandas\\_libs\\lib.pyx in pandas._libs.lib.astype_intsafe()

ValueError: invalid literal for int() with base 10: '8U'
df[df["时长"] == "8U"] #寻找异常值,不知道怎么改的话可以删除

无标题

df.drop([31644], inplace = True)
df["时长"] = df["时长"].astype("int")
df[:5]

无标题

2.2 排序

默认排序

df[:10]

无标题

按照投票人数进行排序

df.sort_values(by = "投票人数", ascending = False)[:5] #默认从小到大

无标题

按照年代进行排序

df.sort_values(by = "年代")[:5]

无标题

多个值排序,先按照评分,再按照投票人数

df.sort_values(by = ["评分","投票人数"], ascending = False) #列表中的顺序决定先后顺序

无标题

2.3 基本统计分析

( 1 )描述性统计

dataframe.describe():对dataframe中的数值型数据进行描述性统计

df.describe()

无标题

通过描述性统计,可以发现一些异常值,很多异常值往往是需要我们逐步去发现的。

df[df["年代"] > 2018] #异常值

Untitled

df[df["时长"] > 1000] #异常值

Untitled

df.drop(df[df["年代"] > 2018].index, inplace = True)
df.drop(df[df["时长"] > 1000].index, inplace = True) #删除异常数据
df.index = range(len(df)) #解决删除后索引不连续的问题

( 2 )最值

df["投票人数"].max()

692795

692795

21

df["评分"].max()

9.9

df["评分"].min()

2.0

( 3 )均值和中值

df["投票人数"].mean()
df["投票人数"].median()
df["评分"].mean()
df["评分"].median()

( 4 )方差和标准差

df["评分"].var()
df["评分"].std()

( 5 )求和

df["投票人数"].sum()

( 6 )相关系数和协方差

df[["投票人数", "评分"]].corr()

import pandas as pd
data = loans_2007[["funded_amnt", "funded_amnt_inv"]]
#计算皮尔逊系数
print(data.corr())
#计算spearman系数
print(data.corr('spearman'))

Untitled

df[["投票人数", "评分"]].cov()

Untitled

( 7 )计数

len(df)

38163

df["产地"].unique() #指定唯一值,取值

array(['美国', '意大利', '中国大陆', '日本', '法国', '英国', '韩国', '中国香港', '阿根廷', '德国', '印度', '其他', '加拿大', '波兰', '泰国', '澳大利亚', '西班牙', '俄罗斯', '中国台湾', '荷兰', '丹麦', '比利时', '巴西', '瑞典', '墨西哥'], dtype=object)

len(df["产地"].unique())

27

产地中包含了一些重复的数据,比如美国和USA,德国和西德,俄罗斯和苏联

我们可以通过数据替换的方法将这些相同国家的电影数据合并一下。

df["产地"].replace("USA","美国",inplace = True) 
#第一个参数是要替换的值,第二个参数是替换后的值
df["产地"].replace(["西德","苏联"],["德国","俄罗斯"], inplace = True) 
#注意一一对应

计算每一年电影的数量:

df["年代"].unique()

array([1994, 1957, 1997, 1993, 2012, 2013, 2003, 2016, 2009, 2008, 2001, 1931, 1961, 2010, 2004, 1998, 1972, 1939, 2015, 1946, 2011, 1982, 1960, 2006, 1988, 2002, 1995, 1996, 1984, 2014, 1953, 2007, 2000, 1967, 1983, 1963, 1977, 1966, 1971, 1974, 1985, 1987, 1973, 1962, 1969, 1989, 1979, 1981, 1936, 1954, 1992, 1970, 1991, 2005, 1920, 1933, 1990, 1999, 1896, 1965, 1921, 1947, 1975, 1964, 1943, 1928, 1986, 1895, 1949, 1932, 1905, 1940, 1908, 1900, 1978, 1951, 1958, 1898, 1976, 1938, 1907, 1948, 1952, 1926, 1955, 1906, 1959, 1934, 1944, 1888, 1909, 1925, 1956, 1923, 1945, 1913, 1903, 1904, 1980, 1968, 1917, 1935, 1942, 1950, 1902, 1941, 1930, 1937, 1922, 1916, 1929, 1927, 1919, 1914, 1912, 1924, 1918, 1899, 1901, 1915, 1892, 1894, 1910, 1897, 1911, 1890, 2018])

len(df["年代"].unique())

127

df["年代"].value_counts(ascending = True)[:10] #默认从大到小

1890 1 2018 1 1892 1 1899 2 1898 2 1888 2 1894 3 1897 3 1911 3 1909 4 Name: 年代, dtype: int64

电影产出前5的国家或地区: