复习:数据分析的第一步,加载数据我们已经学习完毕了。当数据展现在我们面前的时候,我们所要做的第一步就是认识他,今天我们要学习的就是了解字段含义以及初步观察数据。
1 第一章:数据载入及初步观察
1.4 知道你的数据叫什么
我们学习pandas的基础操作,那么上一节通过pandas加载之后的数据,其数据类型是什么呢?
开始前导入numpy和pandas
import numpy as np
import pandas as pd
1.4.1 任务一:pandas中有两个数据类型DateFrame和Series,通过查找简单了解他们。然后自己写一个关于这两个数据类型的小例子🌰[开放题]
Series
Series是一个一维标记数组,能够保存任何数据类型(整数、字符串、浮点数、Python 对象等)。轴标签统称为index。 创建系列的基本方法是调用: s = pd.Series(data, index=index)
-
运算
- s1+s2 #索引相同的元素相加,不同的则补充Nan
- s*2 #所有元素*2
- s+1 #所有元素+1
-
常用方法
- s.index #查看索引
- s.values #查看数值
- s.isnull() #查看为空的,返回布尔型
- s.notnull()
- s.sort_index() #按索引排序
- s.sort_values() #按数值排序
s = pd.Series(['a','b','c','d'])
s
0 a
1 b
2 c
3 d
dtype: object
s = pd.Series(np.random.randn(5), index=["a", "b", "c", "d", "e"])
s
a -0.667947
b 1.078895
c -2.288428
d -0.224024
e -0.170859
dtype: float64
s = pd.Series({"b": 1, "a": 0, "c": 2})
s
b 1
a 0
c 2
dtype: int64
s = pd.Series(5.0, index=["a", "b", "c", "d", "e"])
s
a 5.0
b 5.0
c 5.0
d 5.0
e 5.0
dtype: float64
sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
example_1 = pd.Series(sdata)
example_1
Ohio 35000
Texas 71000
Oregon 16000
Utah 5000
dtype: int64
DataFrame
dataframe是非常常见的一个表格型数据结构,每一列可以是不同的数值类型,有行索引、列索引。提到它就会自然想到Pandas这个包。平常用Python处理xlsx、csv文件,读出来的就是dataframe格式。 DataFrame 接受多种不同类型的输入:
- 一维数组、列表、字典或系列的字典
- 二维 numpy.ndarray
- 结构化或记录ndarray
- 一种 Series
- 其他 DataFrame
data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada', 'Nevada'],
'year': [2000, 2001, 2002, 2001, 2002, 2003],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9, 3.2]}
example_2 = pd.DataFrame(data)
example_2
| state | year | pop |
---|
0 | Ohio | 2000 | 1.5 |
---|
1 | Ohio | 2001 | 1.7 |
---|
2 | Ohio | 2002 | 3.6 |
---|
3 | Nevada | 2001 | 2.4 |
---|
4 | Nevada | 2002 | 2.9 |
---|
5 | Nevada | 2003 | 3.2 |
---|
d = {
"one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
"two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
"three": pd.Series([1.0, 2.0, 3.0, 5.0], index = ["a", "b", "c", "e"])
}
df = pd.DataFrame(d)
df
| one | two | three |
---|
a | 1.0 | 1.0 | 1.0 |
---|
b | 2.0 | 2.0 | 2.0 |
---|
c | 3.0 | 3.0 | 3.0 |
---|
d | NaN | 4.0 | NaN |
---|
e | NaN | NaN | 5.0 |
---|
**Tip:**可以看到,当规定的index数量、名称不一致时,会用NaN补齐表格
df = pd.DataFrame(d, index = ["b", "a", "e"], columns=["two", "three"])
df
| two | three |
---|
b | 2.0 | 2.0 |
---|
a | 1.0 | 1.0 |
---|
e | NaN | 5.0 |
---|
**Tip:**可以通过规定index、columns选取行/列组成表格
1.4.2 任务二:根据上节课的方法载入"train.csv"文件
train_data = pd.read_csv(r"train.csv")
train_data
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked |
---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
---|
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
---|
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
---|
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
---|
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
---|
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
---|
886 | 887 | 0 | 2 | Montvila, Rev. Juozas | male | 27.0 | 0 | 0 | 211536 | 13.0000 | NaN | S |
---|
887 | 888 | 1 | 1 | Graham, Miss. Margaret Edith | female | 19.0 | 0 | 0 | 112053 | 30.0000 | B42 | S |
---|
888 | 889 | 0 | 3 | Johnston, Miss. Catherine Helen "Carrie" | female | NaN | 1 | 2 | W./C. 6607 | 23.4500 | NaN | S |
---|
889 | 890 | 1 | 1 | Behr, Mr. Karl Howell | male | 26.0 | 0 | 0 | 111369 | 30.0000 | C148 | C |
---|
890 | 891 | 0 | 3 | Dooley, Mr. Patrick | male | 32.0 | 0 | 0 | 370376 | 7.7500 | NaN | Q |
---|
891 rows × 12 columns
也可以加载上一节课保存的"train_chinese.csv"文件。通过翻译版train_chinese.csv熟悉了这个数据集,然后我们对trian.csv来进行操作
1.4.3 任务三:查看DataFrame数据的每列的名称
df.columns可以查看表格列名
train_data.columns
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
dtype='object')
1.4.4任务四:查看"Cabin"这列的所有值[有多种方法]
【总结】查看列值的方法: 法一:df[列名] 法二:df.列名
cabin_data = train_data["Cabin"]
cabin_data
0 NaN
1 C85
2 NaN
3 C123
4 NaN
...
886 NaN
887 B42
888 NaN
889 C148
890 NaN
Name: Cabin, Length: 891, dtype: object
cabin_data = train_data.Cabin
cabin_data
0 NaN
1 C85
2 NaN
3 C123
4 NaN
...
886 NaN
887 B42
888 NaN
889 C148
890 NaN
Name: Cabin, Length: 891, dtype: object
1.4.5 任务五:加载文件"test_1.csv",然后对比"train.csv",看看有哪些多出的列,然后将多出的列删除
经过我们的观察发现一个测试集test_1.csv有一列是多余的,我们需要将这个多余的列删去
test_1 = pd.read_csv(r"test_1.csv")
test_1.columns
Index(['Unnamed: 0', 'PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age',
'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked', 'a'],
dtype='object')
【总结】删除列: 法一:df.columns.delete(删除列的位置),若删除多列用[列1位置,……] 法二:del df[列名]
test_1.columns.delete(-1)
Index(['Unnamed: 0', 'PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age',
'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
dtype='object')
del test_1['a']
test_1.columns
Index(['Unnamed: 0', 'PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age',
'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
dtype='object')
1.4.6 任务六: 将[‘PassengerId’,‘Name’,‘Age’,‘Ticket’]这几个列元素隐藏,只观察其他几个列元素
从行或列中删除指定的标签,采用以下语句: DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors=‘raise’)
train_data.drop(columns = ['PassengerId','Name','Age','Ticket'])
train_data.head(3)
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked |
---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
---|
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
---|
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
---|
可以看到,此处依然是全部列数,说明train_data本质并没有发生变化 drop操作后直接观察可以看到隐藏指定列的数据
train_data.drop(columns = ['PassengerId','Name','Age','Ticket']).head(3)
| Survived | Pclass | Sex | SibSp | Parch | Fare | Cabin | Embarked |
---|
0 | 0 | 3 | male | 1 | 0 | 7.2500 | NaN | S |
---|
1 | 1 | 1 | female | 1 | 0 | 71.2833 | C85 | C |
---|
2 | 1 | 3 | female | 0 | 0 | 7.9250 | NaN | S |
---|
如果想要完全的删除数据,使用inplace=True,因为使用inplace就将原数据覆盖了
1.5 筛选的逻辑
表格数据中,最重要的一个功能就是要具有可筛选的能力,选出我所需要的信息,丢弃无用的信息。
下面我们还是用实战来学习pandas这个功能。
1.5.1 任务一: 我们以"Age"为筛选条件,显示年龄在10岁以下的乘客信息。
df[筛选条件]
train_data[train_data['Age']<10]
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked |
---|
7 | 8 | 0 | 3 | Palsson, Master. Gosta Leonard | male | 2.00 | 3 | 1 | 349909 | 21.0750 | NaN | S |
---|
10 | 11 | 1 | 3 | Sandstrom, Miss. Marguerite Rut | female | 4.00 | 1 | 1 | PP 9549 | 16.7000 | G6 | S |
---|
16 | 17 | 0 | 3 | Rice, Master. Eugene | male | 2.00 | 4 | 1 | 382652 | 29.1250 | NaN | Q |
---|
24 | 25 | 0 | 3 | Palsson, Miss. Torborg Danira | female | 8.00 | 3 | 1 | 349909 | 21.0750 | NaN | S |
---|
43 | 44 | 1 | 2 | Laroche, Miss. Simonne Marie Anne Andree | female | 3.00 | 1 | 2 | SC/Paris 2123 | 41.5792 | NaN | C |
---|
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
---|
827 | 828 | 1 | 2 | Mallet, Master. Andre | male | 1.00 | 0 | 2 | S.C./PARIS 2079 | 37.0042 | NaN | C |
---|
831 | 832 | 1 | 2 | Richards, Master. George Sibley | male | 0.83 | 1 | 1 | 29106 | 18.7500 | NaN | S |
---|
850 | 851 | 0 | 3 | Andersson, Master. Sigvard Harald Elias | male | 4.00 | 4 | 2 | 347082 | 31.2750 | NaN | S |
---|
852 | 853 | 0 | 3 | Boulos, Miss. Nourelain | female | 9.00 | 1 | 1 | 2678 | 15.2458 | NaN | C |
---|
869 | 870 | 1 | 3 | Johnson, Master. Harold Theodor | male | 4.00 | 1 | 1 | 347742 | 11.1333 | NaN | S |
---|
62 rows × 12 columns
1.5.2 任务二: 以"Age"为条件,将年龄在10岁以上和50岁以下的乘客信息显示出来,并将这个数据命名为midage
使用**&**表示且
midage = train_data[(train_data["Age"] > 10) & (train_data["Age"] < 50)]
midage
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked |
---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
---|
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
---|
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
---|
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
---|
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
---|
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
---|
885 | 886 | 0 | 3 | Rice, Mrs. William (Margaret Norton) | female | 39.0 | 0 | 5 | 382652 | 29.1250 | NaN | Q |
---|
886 | 887 | 0 | 2 | Montvila, Rev. Juozas | male | 27.0 | 0 | 0 | 211536 | 13.0000 | NaN | S |
---|
887 | 888 | 1 | 1 | Graham, Miss. Margaret Edith | female | 19.0 | 0 | 0 | 112053 | 30.0000 | B42 | S |
---|
889 | 890 | 1 | 1 | Behr, Mr. Karl Howell | male | 26.0 | 0 | 0 | 111369 | 30.0000 | C148 | C |
---|
890 | 891 | 0 | 3 | Dooley, Mr. Patrick | male | 32.0 | 0 | 0 | 370376 | 7.7500 | NaN | Q |
---|
576 rows × 12 columns
【提示】了解pandas的条件筛选方式以及如何使用交集和并集操作
1.5.3 任务三:将midage的数据中第100行的"Pclass"和"Sex"的数据显示出来
【总结】索引: 法一:使用行名和列名,df.loc[[行名], [列名]] 法二:使用行序和列序,df.iloc[[行索引], [列索引]]
midage.loc[100, ["Pclass","Sex"]]
Pclass 3
Sex female
Name: 100, dtype: object
但是,因为midage是对原表筛选得到的,它的行名依然是原表的行名,即其与现表的索引不一定对应,故要对行索引进行更新,使用如下命令: df.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill=’’) 其中,drop=True时,覆盖原索引进行更新;drop=False时,将原索引作为表格的一列数据,增加新索引
midage = midage.reset_index(drop = True)
midage
| PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked |
---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
---|
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
---|
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
---|
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
---|
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
---|
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
---|
571 | 886 | 0 | 3 | Rice, Mrs. William (Margaret Norton) | female | 39.0 | 0 | 5 | 382652 | 29.1250 | NaN | Q |
---|
572 | 887 | 0 | 2 | Montvila, Rev. Juozas | male | 27.0 | 0 | 0 | 211536 | 13.0000 | NaN | S |
---|
573 | 888 | 1 | 1 | Graham, Miss. Margaret Edith | female | 19.0 | 0 | 0 | 112053 | 30.0000 | B42 | S |
---|
574 | 890 | 1 | 1 | Behr, Mr. Karl Howell | male | 26.0 | 0 | 0 | 111369 | 30.0000 | C148 | C |
---|
575 | 891 | 0 | 3 | Dooley, Mr. Patrick | male | 32.0 | 0 | 0 | 370376 | 7.7500 | NaN | Q |
---|
576 rows × 12 columns
midage.loc[[100], ["Pclass","Sex"]]
1.5.4 任务四:使用loc方法将midage的数据中第100,105,108行的"Pclass","Name"和"Sex"的数据显示出来
midage.loc[[100,105,108], ["Pclass","Name","Sex"]]
| Pclass | Name | Sex |
---|
100 | 2 | Byles, Rev. Thomas Roussel Davids | male |
---|
105 | 3 | Cribb, Mr. John Hatfield | male |
---|
108 | 3 | Calic, Mr. Jovo | male |
---|
1.5.5 任务五:使用iloc方法将midage的数据中第100,105,108行的"Pclass","Name"和"Sex"的数据显示出来
midage.columns
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
dtype='object')
midage.iloc[[100,105,108], [2, 3, 4]]
| Pclass | Name | Sex |
---|
100 | 2 | Byles, Rev. Thomas Roussel Davids | male |
---|
105 | 3 | Cribb, Mr. John Hatfield | male |
---|
108 | 3 | Calic, Mr. Jovo | male |
---|
|