参考链接: 创建一个Pandas DataFrame

DataFrame对象的创建,修改,合并

import pandas as pd

import numpy as np

创建DataFrame对象

# 创建DataFrame对象

df = pd.DataFrame([1, 2, 3, 4, 5], columns=['cols'], index=['a','b','c','d','e'])

print df

cols

a     1

b     2

c     3

d     4

e     5

df2 = pd.DataFrame([[1, 2, 3],[4, 5, 6]], columns=['col1','col2','col3'], index=['a','b'])

print df2

col1  col2  col3

a     1     2     3

b     4     5     6

df3 = pd.DataFrame(np.array([[1,2],[3,4]]), columns=['col1','col2'], index=['a','b'])

print df3

col1  col2

a     1     2

b     3     4

df4 = pd.DataFrame({'col1':[1,3],'col2':[2,4]},index=['a','b'])

print df4

col1  col2

a     1     2

b     3     4

创建DataFrame对象的数据可以为列表,数组和字典,列名和索引为列表对象

基本操作

# DataFrame对象的基本操作

df2.index

Index([u'a', u'b'], dtype='object')

df2.columns

Index([u'col1', u'col2', u'col3'], dtype='object')

# 根据索引查看数据

df2.loc['a']

# 索引为a这一行的数据

# df2.iloc[0] 跟上面的操作等价,一个是根据索引名,一个是根据数字索引访问数据

col1    1

col2    2

col3    3

Name: a, dtype: int64

print df2.loc[['a','b']]    # 访问多行数据,索引参数为一个列表对象

col1  col2  col3

a     1     2     3

b     4     5     6

print df.loc[df.index[1:3]]

cols

b     2

c     3

# 访问列数据

print df2[['col1','col3']]

col1  col3

a     1     3

b     4     6

计算

# DataFrame元素求和

# 默认是对每列元素求和

print df2.sum()

col1    5

col2    7

col3    9

dtype: int64

# 行求和

print df2.sum(1)

a     6

b    15

dtype: int64

# 对每个元素乘以2

print df2.apply(lambda x:x*2)

col1  col2  col3

a     2     4     6

b     8    10    12

# 对每个元素求平方(支持ndarray一样的向量化操作)

print df2**2

col1  col2  col3

a     1     4     9

b    16    25    36

列扩充

# 对DataFrame对象进行列扩充

df2['col4'] = ['cnn','rnn']

print df2

col1  col2  col3 col4

a     1     2     3  cnn

b     4     5     6  rnn

# 也可以通过一个新的DataFrame对象来定义一个新列,索引自动对应

df2['col5'] = pd.DataFrame(['MachineLearning','DeepLearning'],index=['a','b'])

print df2

col1  col2  col3 col4             col5

a     1     2     3  cnn  MachineLearning

b     4     5     6  rnn     DeepLearning

行扩充

# 行进行扩充

print df2.append(pd.DataFrame({'col1':7,'col2':8,'col3':9,'col4':'rcnn','col5':'ReinforcementLearning'},index=['c']))

col1  col2  col3  col4                   col5

a     1     2     3   cnn        MachineLearning

b     4     5     6   rnn           DeepLearning

c     7     8     9  rcnn  ReinforcementLearning

注意!

# 如果在进行 行扩充时候没有,指定index的参数,索引会被数字取代

print df2.append({'col1':10,'col2':11,'col3':12,'col4':'frnn','col5':'DRL'},ignore_index=True)

col1  col2  col3  col4             col5

0     1     2     3   cnn  MachineLearning

1     4     5     6   rnn     DeepLearning

2    10    11    12  frnn              DRL

# 以上的行扩充,并没有真正修改,df2这个DataFrame对象,除非

df2 = df2.append(pd.DataFrame({'col1':7,'col2':8,'col3':9,'col4':'rcnn','col5':'ReinforcementLearning'},index=['c']))

print df2

col1  col2  col3  col4                   col5

a     1     2     3   cnn        MachineLearning

b     4     5     6   rnn           DeepLearning

c     7     8     9  rcnn  ReinforcementLearning

c     7     8     9  rcnn  ReinforcementLearning

print df2.loc['c']

col1  col2  col3  col4                   col5

c     7     8     9  rcnn  ReinforcementLearning

c     7     8     9  rcnn  ReinforcementLearning

DataFrame对象的合并

# DataFrame 对象的合并

df_a = pd.DataFrame(['wang','jing','hui','is','a','master'],columns=['col6'],index=['a','b','c','d','e','f'])

print df_a

col6

a    wang

b    jing

c     hui

d      is

e       a

f  master

# 默认合并,只保留dfb中的全部索引

dfb = pd.DataFrame([1,2,4,5,6,7],columns=['col1'],index=['a','b','c','d','f','g'])

print dfb.join(df_a)

col1    col6

a     1    wang

b     2    jing

c     4     hui

d     5      is

f     6  master

g     7     NaN

# 默认合并之接受索引已经存在的值

# 通过指定参数 how,指定合并的方式

print dfb.join(df_a,how='inner')   # 合并两个DataFrame对象的交集

col1    col6

a     1    wang

b     2    jing

c     4     hui

d     5      is

f     6  master

# 合并两个DataFrame对象的并集

print dfb.join(df_a,how='outer')

col1    col6

a   1.0    wang

b   2.0    jing

c   4.0     hui

d   5.0      is

e   NaN       a

f   6.0  master

g   7.0     NaN

安利一下,公众号:唐牛才是食神

[转载] Pandas:DataFrame对象的基础操作相关推荐

  1. pandas.DataFrame的类SQL操作

    前言 pandas的DataFrame是类似于一张表的结构,但是并没有像数据库表那样的SQL操作.虽然如此,它依然可以使用python语言的风格实现SQL中的所有操作. 文章较长,建议点击右侧目录定位 ...

  2. [转载] pandas DataFrame apply()函数(1)

    参考链接: Pandas DataFrame中的转换函数 之前已经写过pandas DataFrame applymap()函数 还有pandas数组(pandas Series)-(5)apply方 ...

  3. [转载] pandas dataframe 提取行和列

    参考链接: 在Pandas DataFrame中处理行和列 import pandas as pd data = pd.DataFrame({'a':[1,2,3],'b':[4,5,6],'c':[ ...

  4. pandas dataframe多重索引常用操作

    增加(创建) df1=pd.DataFrame(np.arange(12).reshape(4,3),index=[list("AABB"),[1,2,1,2]],columns= ...

  5. 使用python pandas dataframe学习数据分析

    ⚠️ Note - This post is a part of Learning data analysis with python series. If you haven't read the ...

  6. Python读取dat文件数据并构成Dataframe对象

    实际应用中,对数据进行处理时,到手的数据文件往往五花八门,data.txt.csv.json等等.Python为我们提供了强大的数据分析处理工具,如果文件符合某种格式要求,可以使用pandas模块中的 ...

  7. pandas教程04---DataFrame的高级操作

    文章目录 欢迎关注公众号[Python开发实战], 获取更多内容! 工具-pandas Dataframe对象 转置 计算表达式 DataFrame查询 DataFrame排序 绘制DataFrame ...

  8. python将ElasticSearch索引数据读入pandas dataframe实战

    python将ElasticSearch索引数据读入pandas dataframe实战 # 导入基础包和库 import pandas as pdpd.set_option('display.max ...

  9. Python小练习2:pandas.Dataframe使用方法示例demo

    pandas.Dataframe使用方法示例demo 本文通过一个实例来介绍pandas.Dataframe的各种常用操作,问题总结并修改自coursera上南京大学的课程:用Python玩转数据. ...

最新文章

  1. Python3 基础语法(笔记1)
  2. Python环境下的数据库编程
  3. JavaScript写贪吃蛇游戏,代码思路都有,想学的自己看
  4. TensorFlow(十)定义图变量的方法
  5. 哈啰单车涨价:起步价1元/15分钟 仅限北京地区
  6. 树的基本定义表示方法
  7. VB编PiView4注册机
  8. 根据文件前四个字节判断文件类型(centos 7)
  9. 认真学习系列:计算机组成原理——哈工网课笔记
  10. Bailian2815 城堡问题【DFS】
  11. EA6900刷梅林教程超详细
  12. 《麦肯锡方法》第8章 展开访谈-思维导图
  13. 硬盘格式化怎么操作 硬盘格式化后数据还在吗
  14. Broken Auth and session mgmt
  15. 【算法讲20:Dsu on Tree】树上数颜色 | Lomsat gelral
  16. html代码 imgn,html代码大全
  17. 索尼手机android怎么连,索尼SmartWatch 2 SW2 连接手机图文教程
  18. 用U深度启动U盘清除系统登入密码
  19. CDA_Level1_学习笔记1
  20. mysql 1044_mysql重置密码和mysql error 1044(42000)错误

热门文章

  1. 【HDOJ 3790】最短路径问题,Dijkstra最短路,双边权
  2. mysql8错误1045_Mysql错误1045解决方法
  3. 页面之间的跳转与交互
  4. maven项目的pom文件中常用的简单的标签理解
  5. html5标签之表单元素
  6. html 内容不被父级包住,解决:父级元素不能被子元素内容撑开的解决办法,父级元素没有高度的解决办法...
  7. 基于范围的for循环
  8. Codeforces Round #468 (Div. 2): C. Laboratory Work(贪心)
  9. matlab2c使用c++实现matlab函数系列教程-nchoosek函数
  10. MySQL(四)InnoDB中一棵B+树能存多少行数据