04_Pandas的数据结构

Pandas的数据结构

导入pandas:
三剑客

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline


from pandas import Series, DataFrame

1、Series

Series是一种类似于一维数组的对象,由下面两个部分组成:

  • values:一组数据(ndarray类型)
  • index:相关的数据索引标签

1)Series的创建

两种创建方式:

(1) 由列表或numpy数组创建

默认索引为0到N-1的整数型索引
n = np.array([0, 2, 4, 6, 8])

# Series和ndarray差别,有没有具体的索引
s = Series(n)
s
0    0
1    2
2    4
3    6
4    8
dtype: int64
# Series包含ndarray
# Series功能就会强大,索引,检索方便很多
s.values
array([0, 2, 4, 6, 8])
n
array([0, 2, 4, 6, 8])



还可以通过设置index参数指定索引
s.index = list('abcde')
s
a    0
b    2
c    4
d    6
e    8
dtype: int64
s.index = ['张三','李四','Michael','sara','lisa']
s
张三         0
李四         2
Michael    4
sara       6
lisa       8
dtype: int64

特别地,由ndarray创建的是引用,而不是副本。对Series元素的改变也会改变原来的ndarray对象中的元素。(列表没有这种情况)

s['张三'] = 100
s
张三         100
李四           2
Michael      4
sara         6
lisa         8
dtype: int64
n
array([100,   2,   4,   6,   8])

(2) 由字典创建

# 字典的key就是索引
s = Series({'a': 1, 'b': 2, 'c': [1, 2, 3]})
s
a            1
b            2
c    [1, 2, 3]
dtype: object
s.values
array([1, 2, list([1, 2, 3])], dtype=object)

============================================

练习1:

使用多种方法创建以下Series,命名为s1:
语文 150
数学 150
英语 150
理综 300

============================================

s1 = Series([150, 150, 150, 300])
s1
s1.index = ['语文', '数学', '英语', '理宗']
s1
语文    150
数学    150
英语    150
理宗    300
dtype: int64
n = np.array([150, 150, 150, 300])
s1 = Series(n)
s1
s1.index = ['语文', '数学', '英语', '理宗']
s1
语文    150
数学    150
英语    150
理宗    300
dtype: int64
s1 = Series(data=[150]*3 + [100], index=['语文', '数学', '英语', '理宗'])
s1
语文    150
数学    150
英语    150
理宗    100
dtype: int64
s1 = Series({'语文': 150, '数学': 150, '英语': 150, '理宗': 300})
s1
语文    150
数学    150
英语    150
理宗    300
dtype: int64

2)Series的索引和切片

可以使用中括号取单个索引(此时返回的是元素类型),或者中括号里一个列表取多个索引(此时返回的仍然是一个Series类型)。分为显示索引和隐式索引:

(1) 显式索引:

- 使用index中的元素作为索引值
- 使用.loc[](推荐)

注意,此时是闭区间

s = Series(data=[1, 2, 3, 4, 5], index=list('abcde'))
s
a    1
b    2
c    3
d    4
e    5
dtype: int64
# 直接使用中括号
s['a']
1
# 使用 .loc[]  location
s.loc['a']
1
# 切片,全闭区间
s['b': 'd']
b    2
c    3
d    4
dtype: int64
s.loc['b': 'd']
b    2
c    3
d    4
dtype: int64

(2) 隐式索引:

- 使用整数作为索引值
- 使用.iloc[](推荐)

注意,此时是半开区间

s = Series(['panky', 'suki', 'snoopy', 'jake', 'disk'], index=[1, 2, 3, 4, 5])
s
1     panky
2      suki
3    snoopy
4      jake
5      disk
dtype: object
s[1]
'panky'
s.iloc[1]
'suki'
s[1: 3]
2      suki
3    snoopy
dtype: object
s.index
Int64Index([1, 2, 3, 4, 5], dtype='int64')
s.iloc[1: 3]
2      suki
3    snoopy
dtype: object

============================================

练习2:

使用多种方法对练习1创建的Series s1进行索引和切片:

索引:
数学 150

切片:
语文 150
数学 150
英语 150

============================================

s = Series(data={'语文': 150, '数学': 150, '英语': 150, '理宗': 300})
s
语文    150
数学    150
英语    150
理宗    300
dtype: int64
s['数学']
150
s.loc['数学']
150
s['语文': '英语']
语文    150
数学    150
英语    150
dtype: int64
s.loc['语文': '英语']
语文    150
数学    150
英语    150
dtype: int64
# 隐式 隐式左闭右开的区间
s.iloc[0: 3]
语文    150
数学    150
英语    150
dtype: int64

3)Series的基本概念

可以把Series看成一个定长的有序字典
可以通过shape,size,index,values等得到series的属性

s = Series(data=[145, 133, 123, 148, 150], index=['panky', 'suki', 'snoopy', 'jake', 'disk'])
s
panky     145
suki      133
snoopy    123
jake      148
disk      150
dtype: int64
s.shape
(5,)
s.size
5
s.values
array([145, 133, 123, 148, 150])
s.index
Index(['panky', 'suki', 'snoopy', 'jake', 'disk'], dtype='object')

可以通过head(),tail()快速查看Series对象的样式

s.head(2)
panky    145
suki     133
dtype: int64
s.tail(2)
jake    148
disk    150
dtype: int64

example_2

ph = pd.read_csv('./president_heights.csv')
ph
ordernameheight(cm)
01George Washington189
12John Adams170
23Thomas Jefferson189
34James Madison163
45James Monroe183
56John Quincy Adams171
67Andrew Jackson185
78Martin Van Buren168
89William Henry Harrison173
910John Tyler183
1011James K. Polk173
1112Zachary Taylor173
1213Millard Fillmore175
1314Franklin Pierce178
1415James Buchanan183
1516Abraham Lincoln193
1617Andrew Johnson178
1718Ulysses S. Grant173
1819Rutherford B. Hayes174
1920James A. Garfield183
2021Chester A. Arthur183
2123Benjamin Harrison168
2225William McKinley170
2326Theodore Roosevelt178
2427William Howard Taft182
2528Woodrow Wilson180
2629Warren G. Harding183
2730Calvin Coolidge178
2831Herbert Hoover182
2932Franklin D. Roosevelt188
3033Harry S. Truman175
3134Dwight D. Eisenhower179
3235John F. Kennedy183
3336Lyndon B. Johnson193
3437Richard Nixon182
3538Gerald Ford183
3639Jimmy Carter177
3740Ronald Reagan185
3841George H. W. Bush188
3942Bill Clinton188
4043George W. Bush182
4144Barack Obama185
s_name = ph['name']
type(s_name)
pandas.core.series.Series
s_name.head(2)
0    George Washington
1           John Adams
Name: name, dtype: object
s_name.tail(2)
40    George W. Bush
41      Barack Obama
Name: name, dtype: object
s_name.tail()
37        Ronald Reagan
38    George H. W. Bush
39         Bill Clinton
40       George W. Bush
41         Barack Obama
Name: name, dtype: object

当索引没有对应的值时,可能出现缺失数据显示NaN(not a number)的情况

s = Series(data=[1, 2, 3, None])
s
0    1.0
1    2.0
2    3.0
3    NaN
dtype: float64

可以使用pd.isnull(),pd.notnull(),或自带isnull(),notnull()函数检测缺失数据

s = Series(['a', None, 'c', None, 'f'])
s
0       a
1    None
2       c
3    None
4       f
dtype: object
pd.isnull(s)
0    False
1     True
2    False
3     True
4    False
dtype: bool
pd.notnull(s)
0     True
1    False
2     True
3    False
4     True
dtype: bool
s.isnull()
0    False
1     True
2    False
3     True
4    False
dtype: bool
s.notnull()
0     True
1    False
2     True
3    False
4     True
dtype: bool

Series对象本身及其实例都有一个name属性

s = Series(data=[1, 2, 3, 4], name='a test')
s
0    1
1    2
2    3
3    4
Name: a test, dtype: int64
Series.name = 'Change'
s
0    1
1    2
2    3
3    4
Name: Change, dtype: int64

4)Series的运算

(1) 适用于numpy的数组运算也适用于Series

s = Series([1, 3, 5, 7], name='odd')
s
0    1
1    3
2    5
3    7
Name: odd, dtype: int64
s + 1
0    2
1    4
2    6
3    8
Name: odd, dtype: int64

(2) Series之间的运算

  • 在运算中自动对齐不同索引的数据
  • 如果索引不对应,则补NaN
s1 = Series([1, 3, 5, 7])
s1
0    1
1    3
2    5
3    7
dtype: int64
s2 = Series([2, 4, 6, 8])
s2
0    2
1    4
2    6
3    8
dtype: int64
s1 + s2
0     3
1     7
2    11
3    15
dtype: int64

Series之间的运算,是对应的index的元素进行运算,index不对应,补 NaN

s3 = Series([1, 2, 3, 4])
s4 = Series([1, 2, 3, 4], index=[2, 3, 4, 5])
s3 + s4
0    NaN
1    NaN
2    4.0
3    6.0
4    NaN
5    NaN
dtype: float64
  • 注意:要想保留所有的index,则需要使用.add()函数
s3.add(s4, fill_value=0)
0    1.0
1    2.0
2    4.0
3    6.0
4    3.0
5    4.0
dtype: float64

============================================

练习3:

  1. 想一想Series运算和ndarray运算的规则有什么不同?

  2. 新建另一个索引包含“文综”的Series s2,并与s2进行多种算术操作。思考如何保存所有数据。

============================================

# Series没有广播机制
s1 = Series(data=[150] * 3 +[300], index=['语文', '数学', '英语', '理宗'])
s2 = Series(data=[150] * 3 +[300], index=['语文', '数学', '英语', '文综'])
s1 + s2
数学    300.0
文综      NaN
理宗      NaN
英语    300.0
语文    300.0
dtype: float64
s1.add(s2, fill_value=0)
数学    300.0
文综    300.0
理宗    300.0
英语    300.0
语文    300.0
dtype: float64

2、DataFrame

DataFrame是一个【表格型】的数据结构,可以看做是【由Series组成的字典】(共用同一个索引)。DataFrame由按一定顺序排列的多列数据组成。设计初衷是将Series的使用场景从一维拓展到多维。DataFrame既有行索引,也有列索引。

  • 行索引:index
  • 列索引:columns
  • 值:values(numpy的二维数组)

1)DataFrame的创建

最常用的方法是传递一个字典来创建。DataFrame以字典的键作为每一【列】的名称,以字典的值(一个数组)作为每一列。

此外,DataFrame会自动加上每一行的索引(和Series一样)。

同Series一样,若传入的列与字典的键不匹配,则相应的值为NaN。

from pandas import DataFrame
df = DataFrame({'语文': np.random.randint(90, 150, size=4),
                '数学': np.random.randint(90, 150, size=4),
                '英语': np.random.randint(90, 150, size=4),
                'coding': np.random.randint(90, 150, size=4)
               })
df.index = ['panky', 'suki', 'lucy', 'loop']
df
语文数学英语coding
panky109128141138
suki136117108134
lucy13294107141
loop11611711290
index = ['panky', 'suki', 'lily', 'loop']
columns = ['Chinese', 'Math', 'English', 'Coding']
data = np.random.randint(90, 150, size=(4, 4))
df2 = DataFrame(index=index, columns=columns, data=data)
df2
ChineseMathEnglishCoding
panky13097142103
suki111140147105
lily134110132128
loop118111112146

DataFrame属性:values、columns、index、shape

df.values
array([[109, 128, 141, 138],
       [136, 117, 108, 134],
       [132,  94, 107, 141],
       [116, 117, 112,  90]])
df.columns
Index(['语文', '数学', '英语', 'coding'], dtype='object')
df.index
Index(['panky', 'suki', 'lucy', 'loop'], dtype='object')
df.shape
(4, 4)

============================================

练习4:

根据以下考试成绩表,创建一个DataFrame,命名为df:

    张三  李四
语文 150  0
数学 150  0
英语 150  0
理综 300  0

============================================

data = [
    [150, 0],
    [150, 0],
    [150, 0],
    [300, 0]
]
columns = ['zhangsan', 'lisi']
index = ['语文', '数学', '英语', '理宗']
df1 = DataFrame(data=data, index= index, columns=columns)
df1
zhangsanlisi
语文1500
数学1500
英语1500
理宗3000
data = {'zhangsan': [150] * 3 + [300],  'lisi': [0] * 4}
index = ['语文', '数学', '英语', '理宗']
df2 = DataFrame(data=data, index=index)
df2
zhangsanlisi
语文1500
数学1500
英语1500
理宗3000

2)DataFrame的索引

(1) 对列进行索引

- 通过类似字典的方式
- 通过属性的方式
 # 行对于DataFrame而言,是样本,不是属性,不能通过.的方式进行调用

可以将DataFrame的列获取为一个Series。返回的Series拥有原DataFrame相同的索引,且name属性也已经设置好了,就是相应的列名。

index = ['panky', 'suki', 'lily', 'loop']
columns = ['Chinese', 'Math', 'English', 'Coding']
data = np.random.randint(90, 150, size=(4, 4))
df = DataFrame(index=index, columns=columns, data=data)
df
ChineseMathEnglishCoding
panky142126115116
suki14013591140
lily1089299131
loop112126102142
# 类似字典的方式 dic['key']
df['Chinese']
panky    142
suki     140
lily     108
loop     112
Name: Chinese, dtype: int64
df[['Math', 'Coding']]  # 两个中括号,还是返回DataFrame
MathCoding
panky126116
suki135140
lily92131
loop126142
df.Chinese
panky    142
suki     140
lily     108
loop     112
Name: Chinese, dtype: int64
[df.Math, df.Coding]
[panky    126
 suki     135
 lily      92
 loop     126
 Name: Math, dtype: int64, panky    116
 suki     140
 lily     131
 loop     142
 Name: Coding, dtype: int64]

(2) 对行进行索引

- 使用.loc[]加index来进行行索引
- 使用.iloc[]加整数来进行行索引

同样返回一个Series,index为原来的columns。

df
ChineseMathEnglishCoding
panky142126115116
suki14013591140
lily1089299131
loop112126102142
df.loc['suki']  # 显式索引
Chinese    140
Math       135
English     91
Coding     140
Name: suki, dtype: int64
df.loc[['loop']]
ChineseMathEnglishCoding
loop112126102142
df.iloc[0]  # 隐式索引
Chinese    142
Math       126
English    115
Coding     116
Name: panky, dtype: int64
df.iloc[[0]]
ChineseMathEnglishCoding
panky142126115116
df.iloc[0: 2]
ChineseMathEnglishCoding
panky142126115116
suki14013591140
df.loc['panky': 'suki']
ChineseMathEnglishCoding
panky142126115116
suki14013591140

(3) 对元素索引的方法
- 使用列索引
- 使用行索引(iloc[3,1]相当于两个参数;iloc[[3,3]] 里面的[3,3]看做一个参数)
- 使用values属性(二维numpy数组)

df
ChineseMathEnglishCoding
panky142126115116
suki14013591140
lily1089299131
loop112126102142
# 先找列再找行
df['English']['suki']
91
df['English'].loc['suki']
91
df['English', 'panky']  # 先找列的时候,不能写到一个中括号中
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2896             try:
-> 2897                 return self._engine.get_loc(key)
   2898             except KeyError:


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


KeyError: ('English', 'panky')


During handling of the above exception, another exception occurred:

KeyError                                  Traceback (most recent call last)

<ipython-input-128-5668b58e37e0> in <module>
----> 1 df['English', 'panky']  # 先找列的时候,不能写到一个中括号中


~/.local/lib/python3.6/site-packages/pandas/core/frame.py in __getitem__(self, key)
   2978             if self.columns.nlevels > 1:
   2979                 return self._getitem_multilevel(key)
-> 2980             indexer = self.columns.get_loc(key)
   2981             if is_integer(indexer):
   2982                 indexer = [indexer]


~/.local/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
   2897                 return self._engine.get_loc(key)
   2898             except KeyError:
-> 2899                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   2900         indexer = self.get_indexer([key], method=method, tolerance=tolerance)
   2901         if indexer.ndim > 1 or indexer.size > 1:


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()


KeyError: ('English', 'panky')
# 先行后列
df.loc['panky']['Math']
126
df.loc['panky'].loc['Math']
126

【注意】
直接用中括号时:

  • 索引表示的是列索引
  • 切片表示的是行切片
df['Math']
panky    126
suki     135
lily      92
loop     126
Name: Math, dtype: int64
df['suki': 'lily']
ChineseMathEnglishCoding
suki14013591140
lily1089299131
df.iloc[1: 3]
ChineseMathEnglishCoding
suki14013591140
lily1089299131

============================================

练习5:

使用多种方法对ddd进行索引和切片,并比较其中的区别

============================================

ddd = DataFrame(data={'张三': [150] * 3 + [300],
                      '李四': [0] * 4
                     }, index=['Chinese', 'Math', 'English', 'Coding'])
ddd
张三李四
Chinese1500
Math1500
English1500
Coding3000

1, 取出张三的语文成绩,要求返回的还是一个DataFrame

type(ddd)
pandas.core.frame.DataFrame
res = ddd['张三'].loc['Chinese']
res
150
type(res)
numpy.int64
res = ddd[0:1]
res
张三李四
Chinese1500
res = ddd.loc[['Chinese'], ['张三']]
res
张三
Chinese150
type(res)
pandas.core.frame.DataFrame

2, 进行行切片,切出数学到编程的数据

ddd['Math': 'Coding']
张三李四
Math1500
English1500
Coding3000
ddd.loc['Math': 'Coding']
张三李四
Math1500
English1500
Coding3000
ddd.iloc[1: 4]
张三李四
Math1500
English1500
Coding3000

3, 对李四的英语成绩赋值, 成绩是88.8分.

ddd['李四'].loc['English'] = 88.8
ddd
张三李四
Chinese1500.0
Math1500.0
English15088.8
Coding3000.0
ddd.loc['Coding', '李四'] = 135.6
ddd
张三李四
Chinese1500.0
Math1500.0
English15088.8
Coding300135.6

4, 增加一列 王五

ddd['王五'] = np.random.randint(0, 150, 4)
ddd
张三李四王五
Chinese1500.05
Math1500.0117
English15088.871
Coding300135.625

5, 新增加一行

ddd.loc['python'] = np.random.randint(0, 150, size=3)
ddd
张三李四王五
Chinese1500.05
Math1500.0117
English15088.871
Coding300135.625
python834.0126

3)DataFrame的运算

(1) DataFrame之间的运算

同Series一样:

  • 在运算中自动对齐不同索引的数据
  • 如果索引不对应,则补NaN

创建DataFrame df1 不同人员的各科目成绩,月考一

df1 = DataFrame({'Python': [122, 133, 140], 'Math': [139, 118, 112],
                 'English': [133, 128, 110]
                }, index=['A', 'B', 'C'])
df1
PythonMathEnglish
A122139133
B133118128
C140112110

创建DataFrame df2 不同人员的各科目成绩,月考二
有新学生转入

df2 = DataFrame(data=np.random.randint(0, 150, size=(4, 4)),
                index=['A', 'B', 'C', 'D'],
                columns=['Python', 'Math', 'Physical', 'English']
               )
df2
PythonMathPhysicalEnglish
A10449871
B8212334113
C261463123
D55814723
df1
PythonMathEnglish
A122139133
B133118128
C140112110
# + 生成一个新的DataFrame
df1 + 10
PythonMathEnglish
A132149143
B143128138
C150122120
df1 + df2
EnglishMathPhysicalPython
A204.0188.0NaN226.0
B241.0241.0NaN215.0
C233.0258.0NaN166.0
DNaNNaNNaNNaN

下面是Python 操作符与pandas操作函数的对应表:

Python OperatorPandas Method(s)
+add()
-sub(), subtract()
*mul(), multiply()
/truediv(), div(), divide()
//floordiv()
%mod()
**pow()
display(df1, df2)
PythonMathEnglish
A122139133
B133118128
C140112110
PythonMathPhysicalEnglish
A10449871
B8212334113
C261463123
D55814723
df = df1.add(df2, fill_value=0)/2
df
EnglishMathPhysicalPython
A102.094.04.0113.0
B120.5120.517.0107.5
C116.5129.01.583.0
D11.540.523.527.5

(2) Series与DataFrame之间的运算

【重要】

  • 使用Python操作符:以行为单位操作(参数必须是行),对所有行都有效。(类似于numpy中二维数组与一维数组的运算,但可能出现NaN)

  • 使用pandas操作函数:
    • axis=0:以列为单位操作(参数必须是列),对所有列都有效。
    • axis=1:以行为单位操作(参数必须是行),对所有行都有效。
    • Whether to compare by the index (0 or 'index') or columns(1 or 'columns'). For Series input, axis to match Series index on.
s = Series([69.0, 130.0, 70.5, 85.5, 10.0], index=['Python', 'Math', 'Physical', 'English', 'Golang'])
s
Python       69.0
Math        130.0
Physical     70.5
English      85.5
Golang       10.0
dtype: float64
data = np.random.randint(90, 150, size=(5, 4))
columns = ['Python', 'Math', 'Physical', 'English']
index = ['Michael', 'San', 'Si', 'Wu', 'Fly']
df = DataFrame(data=data, columns=columns, index=index)
df
PythonMathPhysicalEnglish
Michael94126102134
San1249898128
Si119139130115
Wu1369399121
Fly135121147125

s
Python       69.0
Math        130.0
Physical     70.5
English      85.5
Golang       10.0
dtype: float64
# 以行为单位,操作每一行,加s
df.add(s, axis=1)
EnglishGolangMathPhysicalPython
Michael219.5NaN256.0172.5163.0
San213.5NaN228.0168.5193.0
Si200.5NaN269.0200.5188.0
Wu206.5NaN223.0169.5205.0
Fly210.5NaN251.0217.5204.0
df.add(s, axis=0)
PythonMathPhysicalEnglish
EnglishNaNNaNNaNNaN
FlyNaNNaNNaNNaN
GolangNaNNaNNaNNaN
MathNaNNaNNaNNaN
MichaelNaNNaNNaNNaN
PhysicalNaNNaNNaNNaN
PythonNaNNaNNaNNaN
SanNaNNaNNaNNaN
SiNaNNaNNaNNaN
WuNaNNaNNaNNaN

s2 = Series([98, 120, 130, 120],
            index=['Michael', 'San', 'Si', 'Wu'], name='Python')
s2
Michael     98
San        120
Si         130
Wu         120
Name: Python, dtype: int64
df
PythonMathPhysicalEnglish
Michael94126102134
San1249898128
Si119139130115
Wu1369399121
Fly135121147125
df.add(s2, axis=0)
PythonMathPhysicalEnglish
FlyNaNNaNNaNNaN
Michael192.0224.0200.0232.0
San244.0218.0218.0248.0
Si249.0269.0260.0245.0
Wu256.0213.0219.0241.0

s3 = df['Python']
s3
Michael     94
San        124
Si         119
Wu         136
Fly        135
Name: Python, dtype: int64
# s3 和 df 进行操作
# 结论: DataFrame 和Series运算 的时候,默认 是对比列索引.列索引一致才能运算.否则补NaN.
df + s3
EnglishFlyMathMichaelPhysicalPythonSanSiWu
MichaelNaNNaNNaNNaNNaNNaNNaNNaNNaN
SanNaNNaNNaNNaNNaNNaNNaNNaNNaN
SiNaNNaNNaNNaNNaNNaNNaNNaNNaN
WuNaNNaNNaNNaNNaNNaNNaNNaNNaN
FlyNaNNaNNaNNaNNaNNaNNaNNaNNaN

============================================

练习6:

  1. 假设ddd是期中考试成绩,ddd2是期末考试成绩,请自由创建ddd2,并将其与ddd相加,求期中期末平均值。

  2. 假设cat期中考试数学被发现作弊,要记为0分,如何实现?

  3. dog因为举报张三作弊立功,期中考试所有科目加100分,如何实现?

  4. 后来老师发现有一道题出错了,为了安抚学生情绪,给每位学生每个科目都加10分,如何实现?

============================================

1

data = np.random.randint(0, 150, size=(6, 4))
columns = ['Chinese', 'Math', 'English', 'Python']
index = ['add', 'bit', 'cat', 'dog', 'egg', 'golf']
ddd = DataFrame(data=data, columns=columns, index=index)
ddd
ChineseMathEnglishPython
add763959148
bit7541484
cat49770148
dog32229571
egg933811668
golf33479439
data = np.random.randint(0, 150, size=(6, 4))
columns = ['Chinese', 'Math', 'English', 'Python']
index = ['add', 'bit', 'cat', 'dog', 'egg', 'golf']
ddd2 = DataFrame(data=data, columns=columns, index=index)
ddd2
ChineseMathEnglishPython
add901008764
bit12235120145
cat117756119
dog361374980
egg841149657
golf75275849
(ddd + ddd2) / 2
ChineseMathEnglishPython
add83.069.573.0106.0
bit98.538.084.074.5
cat83.076.030.583.5
dog34.079.572.075.5
egg88.576.0106.062.5
golf54.037.076.044.0

2

ddd.loc['cat'] = 0
ddd
ChineseMathEnglishPython
add763959148
bit7541484
cat0000
dog32229571
egg933811668
golf33479439

3

ddd.loc['dog']
Chinese    32
Math       22
English    95
Python     71
Name: dog, dtype: int64
ddd.loc['dog'] += 100
ddd
ChineseMathEnglishPython
add763959148
bit7541484
cat0000
dog132122195171
egg933811668
golf33479439

4

ddd
ChineseMathEnglishPython
add763959148
bit7541484
cat0000
dog132122195171
egg933811668
golf33479439
ddd += 10
ddd
ChineseMathEnglishPython
add864969158
bit85515814
cat10101010
dog142132205181
egg1034812678
golf435710449

转载于:https://www.cnblogs.com/pankypan/p/11567937.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值