数据挖掘 pandas基础入门之创建对象

pandas是一个提供快速,灵活和表达性数据结构的Python包,旨在使“关系”或“标记”数据变得简单直观。它旨在成为在Python中进行实用的真实世界数据分析的基本高级构建块。

pandas非常适合许多不同类型的数据:

  • 具有非均匀类型列的表格数据,如在SQL表或Excel电子表格中
  • 有序和无序(不一定是固定频率)时间序列数据。
  • 带有行和列标签的任意矩阵数据(均匀类型或异质)
  • 任何其他形式的观测/统计数据集。数据实际上不需要被标记就可以被放置到Pandas的数据结构中

pandas的两个主要数据结构Series(一维)和Dataframe(二维)处理了金融,统计,社会中的绝大多数典型用例科学,以及许多工程领域。

创建对象

import pandas
import numpy

# 可以通过传递一个list对象来创建一个Series,pandas会默认创建整型索引
s = pandas.Series([1, 3, 5, numpy.nan, 6, 8])
print("通过传递一个list对象来创建一个Series:", s, sep="\n")

# 通过传递一个 numpyarray,时间索引以及列标签来创建一个DataFrame:
dates = pandas.date_range("20180509", periods=6)
print("时间索引: \n", dates)
df = pandas.DataFrame(numpy.random.randn(6, 4), index=dates, columns=list('ABCD'))
print("时间索引以及列标签来创建一个DataFrame:", df, sep="\n")

# 通过传递一个能够被转换成类似序列结构的字典对象来创建一个DataFrame
df = pandas.DataFrame({# 类集合
    "A": 1,
    "B": pandas.Timestamp("20180509"),
    "C": pandas.Series(1, index=list(range(4)), dtype=float),  # Series数组
    "D": numpy.array([3]*4, dtype=int),  # 数组
    "E": pandas.Categorical(["test", "train", "test", "train"]),  # Categorical按某一列重新编码分类
    "F": "foo"
})
print("字典对象来创建一个DataFrame", df, sep="\n")

# 查看不同列的数据类型
print("df.type: ", df.dtypes, sep="\n")

"E:\Python 3.6.2\python.exe" F:/PycharmProjects/test.py
通过传递一个list对象来创建一个Series:
0    1.0
1    3.0
2    5.0
3    NaN
4    6.0
5    8.0
dtype: float64
时间索引: 
 DatetimeIndex(['2018-05-09', '2018-05-10', '2018-05-11', '2018-05-12',
               '2018-05-13', '2018-05-14'],
              dtype='datetime64[ns]', freq='D')
时间索引以及列标签来创建一个DataFrame:
                   A         B         C         D
2018-05-09 -0.243263 -0.340719 -0.043909  0.248548
2018-05-10  2.720385  1.124380 -1.119360  0.610999
2018-05-11 -0.375457 -1.193914  1.132776  2.094997
2018-05-12 -0.435122  0.475113  1.294536 -0.027811
2018-05-13  0.038138 -0.820069  0.744213 -1.301014
2018-05-14 -1.937454 -1.693728 -1.011248 -2.689147
字典对象来创建一个DataFrame
   A          B    C  D      E    F
0  1 2018-05-09  1.0  3   test  foo
1  1 2018-05-09  1.0  3  train  foo
2  1 2018-05-09  1.0  3   test  foo
3  1 2018-05-09  1.0  3  train  foo
df.type: 
A             int64
B    datetime64[ns]
C           float64
D             int32
E          category
F            object
dtype: object

Process finished with exit code 0

猜你喜欢

转载自my.oschina.net/gain/blog/1809769