Implementation code for the Python pandas DataFrame operation

  • 2021-06-29 11:39:37
  • OfStack

1. Create Dataframe from a dictionary


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

2. Create Dataframe from a list (first convert the list into a dictionary, then the dictionary into an DataFrame)


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

3. Create DataFrame from the list, specifying data and 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 sex
0 001 zhangsan  M
1 002   lisi  F
2 003  wangwu  M

4. Modify the column name from ['id','name','sex'] to ['Id','Name','Sex']


>>> df.columns = ['Id','Name','Sex']
>>> df
  Id   Name Sex
0 001 zhangsan  M
1 002   lisi  F
2 003  wangwu  M

5. Adjust DataFrame column order and column number from 1
https://www.ofstack.com/article/163644.htm

6. DataFrame randomly generates 10 rows and 4 columns of int-type data


>>> import pandas
>>> import numpy
>>> df = pandas.DataFrame(numpy.random.randint(0,100,size=(10, 4)), columns=list('ABCD')) # 0,100 Specify random number 0 reach 100 Between (including) 0 Excluding 100 ), size = (10,4) Specify data as 10 That's ok 4 Column, column Specify Column Name 
>>> df
  A  B  C  D
0 67 28 37 66
1 21 27 43 37
2 73 54 98 85
3 40 78  4 93
4 99 60 63 16
5 48 46 24 61
6 59 52 62 28
7 20 74 36 64
8 14 13 46 60
9 18 44 70 36

7. Use time series as index name


>>> df #  Original index For auto-generated 0~9
  A  B  C  D
0 31 25 45 67
1 62 12 61 88
2 79 36 20 97
3 26 57 50 44
4 24 12 50  1
5  4 61 99 62
6 40 47 52 27
7 83 66 71  4
8 58 59 25 62
9 38 81 60  8
>>> import pandas
>>> dates = pandas.date_range('20180121',periods=10)
>>> dates #  from 20180121 Start, total 10 day 
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 #  take dates Assign to index
>>> df
       A  B  C  D
2018-01-21 31 25 45 67
2018-01-22 62 12 61 88
2018-01-23 79 36 20 97
2018-01-24 26 57 50 44
2018-01-25 24 12 50  1
2018-01-26  4 61 99 62
2018-01-27 40 47 52 27
2018-01-28 83 66 71  4
2018-01-29 58 59 25 62
2018-01-30 38 81 60  8

8. dataframe implements class SQL operation

pandas official document Comparison with SQL

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


Related articles: