Pandas之DataFrame对象大总结

一、什么是DataFrame?

DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同类型的值。DataFrame既有行索引也有列索引,它可以被看做是由Series组成的字典(共用同一个索引),数据是以二维结构存放的。

  • 类似多维数组/表格数据 (如,excel, R中的data.frame)
  • 每列数据可以是不同的类型
  • 索引包括列索引和行索引

二、创建DataFrame对象

DataFrame 构造方法如下:

pandas.DataFrame( data, index, columns, dtype, copy)

参数说明:

  • data:一组数据(ndarray、series, map, lists, dict 等类型)。

  • index:索引值,或者可以称为行标签。

  • columns:列标签,默认为 RangeIndex (0, 1, 2, …, n) 。

  • dtype:数据类型。

  • copy:拷贝数据,默认为 False。

1. list列表构建DataFrame

1)通过单列表创建

>>> import pandas as pd
>>>
>>> data = [0, 1, 2, 3, 4, 5]
>>> df = pd.DataFrame(data)
>>> print(df)
   0
0  0
1  1
2  2
3  3
4  4
5  5
>>> print(type(df))
<class 'pandas.core.frame.DataFrame'>

2)通过嵌套列表创建

>>> import pandas as pd
>>>
>>> data = [['小明', 20], ['小红', 10]]
>>> df = pd.DataFrame(data, columns=['name', 'age'], dtype=float)
sys:1: FutureWarning: Could not cast to float64, falling back to object. This behavior is deprecated. In a future version, when a dtype is passed to 'DataFrame', either all columns will be cast to that dtype, or a TypeError will be raised
>>> print(df)
  name   age
0   小明  20.0
1   小红  10.0
>>> print(type(df))
<class 'pandas.core.frame.DataFrame'>

3)列表中嵌套字典(字典的键被用作列名,缺失则赋值为NaN):

>>> import pandas as pd
>>>
>>> data = [{
 'A': 1, 'B': 2}, {
 'A': 3, 'B': 4, 'C': 5}]
>&
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值