pandas基础使用

Pandas是一个强大的分析结构化数据的工具集,基于NumPy构建,提供了高级数据结构和数据操作工具,它是使Python成为强大而高效的数据分析环境的重要因素之一

1、pandas的数据结构

(1)Series

Series是一种类似于一维数组的对象,组成:

一组数据(各种NumPy数据类型)

一组与之对应的索引(数据标签)

索引(index)在左,数据(values)在右

索引是自动创建的

a 通过list构建Series

import pandas as pd
ser_obj = pd.Series(range(1, 5))
print(ser_obj)
print(ser_obj.head(3))  # 打印前三行数据
print(type(ser_obj))    # 打印数据类型
0    1
1    2
2    3
3    4
dtype: int64
0    1
1    2
2    3
dtype: int64
<class 'pandas.core.series.Series'>

b 用字典创建Series

dic = {1000: "hello", 2000: "world", 3000: "!"}
ser_obj = pd.Series(dic)
print(ser_obj)
1000    hello
2000    world
3000        !
dtype: object

(2)DataFrame

一个表格型的数据结构,它含有一组有序的列,每列可以是不同类型的值。DataFrame既有行索引也有列索引,数据是以二维结构存放的。

类似多维数组/表格数据 (如,excel, R中的data.frame)

每列数据可以是不同的类型

索引包括列索引和行索引

a 通过ndarray创建DataFrame

import numpy as np
arr_obj = np.random.rand(3, 4)
df_obj = pd.DataFrame(arr_obj)
print(df_obj)
print(df_obj.head(2))   # 看前两行
          0         1         2         3
0  0.857111  0.125885  0.080517  0.279508
1  0.046565  0.500215  0.334141  0.048163
2  0.741607  0.503988  0.526194  0.885707
          0         1         2         3
0  0.857111  0.125885  0.080517  0.279508
1  0.046565  0.500215  0.334141  0.048163

b 通过dict创建DataFrame

dic = {
    "A": 1,
    "B": pd.Timestamp("20171212"),
    "C": pd.Series(range(10,14), dtype="float64"),
    "D": ["python", "java", "c++", "c"]}
df_obj = pd.DataFrame(dic)
print(df_obj)
   A          B     C       D
0  1 2017-12-12  10.0  python
1  1 2017-12-12  11.0    java
2  1 2017-12-12  12.0     c++
3  1 2017-12-12  13.0       c

猜你喜欢

转载自blog.csdn.net/qwerLoL123456/article/details/82584690