首页 > 编程 > Python > 正文

Python pandas DataFrame操作的实现代码

2019-11-25 12:41:19
字体:
来源:转载
供稿:网友

1. 从字典创建Dataframe

>>> import pandas as pd>>> dict1 = {'col1':[1,2,5,7],'col2':['a','b','c','d']}>>> df = pd.DataFrame(dict1)>>> df  col1 col20   1  a1   2  b2   5  c3   7  d

2. 从列表创建Dataframe (先把列表转化为字典,再把字典转化为DataFrame)

>>> lista = [1,2,5,7]>>> listb = ['a','b','c','d']>>> df = pd.DataFrame({'col1':lista,'col2':listb})>>> df  col1 col20   1  a1   2  b2   5  c3   7  d
 

3. 从列表创建DataFrame,指定data和columns

>>> a = ['001','zhangsan','M']>>> b = ['002','lisi','F']>>> c = ['003','wangwu','M']>>> df = pandas.DataFrame(data=[a,b,c],columns=['id','name','sex'])>>> df  id   name sex0 001 zhangsan  M1 002   lisi  F2 003  wangwu  M

4. 修改列名,从['id','name','sex']修改为['Id','Name','Sex']

>>> df.columns = ['Id','Name','Sex']>>> df  Id   Name Sex0 001 zhangsan  M1 002   lisi  F2 003  wangwu  M

5. 调整DataFrame列顺序、调整列编号从1开始
https://www.VeVB.COm/article/163644.htm

6. DataFrame随机生成10行4列int型数据

>>> import pandas>>> import numpy>>> df = pandas.DataFrame(numpy.random.randint(0,100,size=(10, 4)), columns=list('ABCD')) # 0,100指定随机数为0到100之间(包括0,不包括100),size = (10,4)指定数据为10行4列,column指定列名>>> df  A  B  C  D0 67 28 37 661 21 27 43 372 73 54 98 853 40 78  4 934 99 60 63 165 48 46 24 616 59 52 62 287 20 74 36 648 14 13 46 609 18 44 70 36

7. 用时间序列做index名

>>> df # 原本index为自动生成的0~9  A  B  C  D0 31 25 45 671 62 12 61 882 79 36 20 973 26 57 50 444 24 12 50  15  4 61 99 626 40 47 52 277 83 66 71  48 58 59 25 629 38 81 60  8>>> import pandas>>> dates = pandas.date_range('20180121',periods=10)>>> dates # 从20180121开始,共10天DatetimeIndex(['2018-01-21', '2018-01-22', '2018-01-23', '2018-01-24',        '2018-01-25', '2018-01-26', '2018-01-27', '2018-01-28',        '2018-01-29', '2018-01-30'],       dtype='datetime64[ns]', freq='D')>>> df.index = dates # 将dates赋值给index>>> df       A  B  C  D2018-01-21 31 25 45 672018-01-22 62 12 61 882018-01-23 79 36 20 972018-01-24 26 57 50 442018-01-25 24 12 50  12018-01-26  4 61 99 622018-01-27 40 47 52 272018-01-28 83 66 71  42018-01-29 58 59 25 622018-01-30 38 81 60  8

8. dataframe 实现类SQL操作

pandas官方文档 Comparison with SQL

https://pandas.pydata.org/pandas-docs/stable/comparison_with_sql.html

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表