一、pandas 数据表表示
DataFrame是一种二维数据结构,可以在列中存储不同类型的数据(包括字符、整数、浮点值、分类数据等)。数据表存储在 DataFrame中。
1、 我想存储泰坦尼克号的乘客数据。对于一些乘客,我知道姓名(字符)、年龄(整数)和性别(男/女)数据。
# 该表有 3 列,每列都有一个列标签。列标签分别为 Name、Age和Sex。
# 列 Name由文本数据组成,每个值都是一个字符串,列 Age是数字,列 Sex是文本数据。
In [2]: df = pd.DataFrame(
...: {
...: "Name": [
...: "Braund, Mr. Owen Harris",
...: "Allen, Mr. William Henry",
...: "Bonnell, Miss. Elizabeth",
...: ],
...: "Age": [22, 35, 58],
...: "Sex": ["male", "male", "female"],
...: }
...: )
...:
In [3]: df
Out[3]:
Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
2、在电子表格软件中,我们数据的表格表示看起来非常相似:
二、Series 的表示
每一列DataFrame都是一个Series。
1、DataFrame中获取Age列中的值。
In [4]: df["Age"]
Out[4]:
0 22
1 35
2 58
Name: Age, dtype: int64
2、 Series 列的创建:
In [5]: ages = pd.Series([22, 35, 58], name="Age")
In [6]: ages
Out[6]:
0 22
1 35
2 58
Name: Age, dtype: int64
参考官方文档。