Python刷题系列(8)_Pandas_Dataframe(上)

简介: Python刷题系列(8)_Pandas_Dataframe

Pandas_Dataframe



c508a389f345419fb5750fb5ae4ff2c9.png


1、按元素获取数组值的幂


编写一个 Pandas 程序,以从元素上获取数组值的幂。

  • 注意:第一个数组元素从第二个数组提升为幂
  • 示例数据:
{'X':[78,85,96,80,86],
'Y':[84,94,89,83,86],
'Z':[86,97,96,72,83]}


  • 预期输出:
  X  Y Z
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83

解答:

import pandas as pd
df = pd.DataFrame({'X':[78,85,96,80,86], 
                   'Y':[84,94,89,83,86],
                   'Z':[86,97,96,72,83]});
print(df)

17855c8b57de4d66a02ba595adc47e39.pngb6e8e571ca3e47a3b41affbfd5b09397.png


2、从具有索引标签的字典数据创建数据帧


编写一个 Pandas 程序,以从具有索引标签的指定字典数据创建和显示 DataFrame

示例数据帧:


exam_data =

{‘name’: [‘Anastasia’, ‘Dima’, ‘Katherine’, ‘James’, ‘Emily’, ‘Michael’, ‘Matthew’, ‘Laura’, ‘Kevin’, ‘Jonas’],

‘score’: [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

‘trys’: [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

‘qualify’: [‘yes’, ‘no’, ‘no’, ‘yes’, ‘yes’, ‘no’, ‘yes’, ‘no’, ‘yes’]}


labels = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’]

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df)

0a5c92b72e0e466caec7a7e816cef7b6.png


3、显示有关指定数据帧及其数据的基本信息摘要


编写 Pandas 程序以显示有关指定数据帧及其数据的基本信息的摘要。转到编辑器


示例Python字典数据和列表标签:

exam_data = {‘name’: [‘Anastasia’, ‘Dima’, ‘Katherine’, ‘James’, ‘Emily’, ‘Michael’, ‘Matthew’, ‘Laura’, ‘Kevin’, ‘Jonas’],

‘score’: [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

‘trys’: [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

‘qualify’: [‘yes’, ‘no’, ‘no’, ‘no’, ‘yes’, ‘no’, ‘yes’, ‘no’, ‘no’, ‘’ ‘yes’]}

标签 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’]


预期输出:

有关此 DataFrame 及其数据的基本信息摘要:

<类 ‘pandas.core.frame.DataFrame’>

索引: 10 个条目, a to j

数据列 (总共 4 列):

…dtypes: float64(1), int64(1), object(2)

内存使用情况: 400.0+ 字节


image.png



4、获取给定数据帧的前 3 行


  • 示例Python字典数据和列表标签:


exam_data = {‘name’: [‘Anastasia’, ‘Dima’, ‘Katherine’, ‘James’, ‘Emily’, ‘Michael’, ‘Matthew’, ‘Laura’, ‘Kevin’, ‘Jonas’],

‘score’: [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

‘trys’: [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

‘qualify’: [‘yes’, ‘no’, ‘no’, ‘no’, ‘yes’, ‘no’, ‘yes’, ‘no’, ‘no’, ‘’ ‘yes’]}

标签 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’]


预期输出:

a 1 Anastasia yes 12.5

b 3 Dima no 9.0

c 2 Katherine yes 16.5

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df) 
print("\n")
print(df.iloc[:3])
print("\n")
print(df.head(3))
print("\n")
print(df.iloc[0:1,1:3])

6b0a175573df44258e34d902f7f8ef17.png


5、从给定的数据帧中选择两个指定的列


编写一个 Pandas 程序,从以下数据帧中选择“名称”和“评分”列。

  • 示例Python字典数据和列表标签:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'trys': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'no', 'no', 'yes', 'no', 'yes', 'no', 'no', '' 'yes']}
标签 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  • 预期输出:
a Anastasia 12.5
b Dima 9.0
c Katherine 16.5
...h Laura NaN
i Kevin 8.0
j Jonas 19.0

解答:

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
print(df)
print("\n")
df = pd.DataFrame(exam_data , index=labels)
print(df[['name', 'score']])

302b34cfd7064bce9c5d29aa828083ef.png


6、从给定的数据帧中选择指定的列和行


编写一个 Pandas 程序,从给定的数据帧中选择指定的列和行。转到编辑器

  • 示例 Python 字典数据并列出标签:

从以下数据框中选择第 1、3、5、6 行中的“name”和“score”列。

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'trys': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  • 预期输出:
b 9.0 no
d NaN no
f 20.0 yes
g 14.5 yes

解答:

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df) 
print("\n") 
print(df.iloc[[1, 3, 5, 6], [1, 3]])

cc953e265a2440ce90eaa290acdc4988.png


7、选择检查中尝试次数大于 2 的行


编写 Pandas 程序,选择考试中尝试次数大于 2 的行。

  • 示例Python字典数据和列表标签:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'trys': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'no', 'no', 'yes', 'no', 'yes', 'no', 'no', '' 'yes']}
标签 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']


  • 预期输出:

考试中的尝试次数大于 2,且名称分数尝试次数合格。

b Dima 9.0 3 no
d James NaN 3 no
f Michael 20.0 3 是


解答:

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts' : [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Number of attempts in the examination is greater than 2:")
print(df[df['attempts'] > 2])

关键:df[df['attempts'] > 2]df['attempts'] > 2判断每行是否满足该条件,若满足,则是True,我的理解是布尔索引。


ea2bc311902d40f7ac422934a8deed7e.png


8、计算数据帧的行数和列数


编写一个 Pandas 程序来计算 DataFrame 的行数和列数。转到编辑器

  • 示例Python字典数据和列表标签:


exam_data = {‘name’: [‘Anastasia’, ‘Dima’, ‘Katherine’, ‘James’, ‘Emily’, ‘Michael’, ‘Matthew’, ‘Laura’, ‘Kevin’, ‘Jonas’],

‘score’: [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

‘trys’: [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

‘qualify’: [‘yes’, ‘no’, ‘no’, ‘no’, ‘yes’, ‘no’, ‘yes’, ‘no’, ‘no’, ‘’ ‘yes’]}

标签 = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’]


预期输出:

行数: 10

列数: 4


关键:

【1】计算数据帧的行数:len(df.axes[0])

【2】计算数据帧的列数:len(df.axes[1])

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
total_rows=len(df.axes[0])
total_cols=len(df.axes[1])
print(df)
print("\n")
print("Number of Rows: "+str(total_rows))
print("Number of Columns: "+str(total_cols))

c0ad877e0f22483fa0003db7eeff2ca6.png


9、打印数据缺失的行


打印分数列中含有缺失数值的行

关键点:df[df['score'].isnull()]

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Rows where score is missing:")
print(df[df['score'].isnull()])

e6489d1b2d7d451e992f4a90792e77d8.png


10、打印行,数据在15到20之间


打印分数列中,数据在15到20之间的(含)

关键:df[df['score'].between(15, 20)]

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df) 
print("\n")
print(df[df['score'].between(15, 20)])

3ec001e81433424db18496583035559e.png


11、打印某一列的平均值


打印分数列的平均值

关键:df['score'].mean()

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df) 
print("\n")
print(df['score'].mean())

8b21756841cf4dd59f5f65283a24687e.png


注:如果是求总和的话就把mean()改成sum()即可


12、打印数据帧中多条件的行


编写一个 Pandas 程序,以选择考试中尝试次数小于 2 且分数大于 15 的行。

关键:df[(df[‘attempts’] < 2) & (df[‘score’] > 10)]

注:多条件则必须要在条件外添加括号

import pandas as pd
import numpy as np
exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("attempts列小于2并且score列大于10的行:")
print(df[(df['attempts'] < 2) & (df['score'] > 10)])

e72437a0499b4211aa387eac95878159.png



相关文章
|
3天前
|
数据挖掘 数据处理 索引
python常用pandas函数nlargest / nsmallest及其手动实现
python常用pandas函数nlargest / nsmallest及其手动实现
18 0
|
4天前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名
【4月更文挑战第22天】Pandas Python库提供数据排序和排名功能。使用`sort_values()`按列进行升序或降序排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`。`rank()`函数用于计算排名,如`df[&#39;A&#39;].rank(ascending=False)`。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`和分别对&#39;A&#39;、&#39;B&#39;列排名。
14 2
|
1月前
|
数据格式 Python
如何使用Python的Pandas库进行数据透视图(melt/cast)操作?
Pandas的`melt()`和`pivot()`函数用于数据透视。基本步骤:导入pandas,创建DataFrame,然后使用这两个函数转换数据格式。示例代码展示了如何通过`melt()`转为长格式,再用`pivot()`恢复为宽格式。输入数据是包含&#39;Name&#39;和&#39;Age&#39;列的DataFrame,最终结果经过转换后呈现出不同的布局。
40 6
|
1月前
|
数据处理 Python
如何使用Python的Pandas库进行数据排序和排名?
Pandas在Python中提供数据排序和排名功能。使用`sort_values()`进行排序,如`df.sort_values(by=&#39;A&#39;, ascending=False)`进行降序排序;用`rank()`进行排名,如`df[&#39;A&#39;].rank(ascending=False)`进行降序排名。多列操作可传入列名列表,如`df.sort_values(by=[&#39;A&#39;, &#39;B&#39;], ascending=[True, False])`。
25 6
|
1月前
|
索引 Python
如何使用Python的Pandas库进行数据合并和拼接?
【2月更文挑战第28天】【2月更文挑战第103篇】如何使用Python的Pandas库进行数据合并和拼接?
|
1月前
|
BI 数据处理 索引
Pandas基本操作:Series和DataFrame(Python)
Pandas基本操作:Series和DataFrame(Python)
105 1
|
1月前
|
索引 Python
如何在Python中,Pandas库实现对数据的时间序列分析?
Pandas在Python中提供强大的时间序列分析功能,包括:1) 使用`pd.date_range()`创建时间序列;2) 通过`pd.DataFrame()`将时间序列转为DataFrame;3) `set_index()`设定时间列作为索引;4) `resample()`实现数据重采样(如按月、季度);5) `rolling()`进行移动窗口计算,如计算移动平均;6) 使用`seasonal_decompose()`进行季节性调整。这些工具适用于各种时间序列分析场景。
35 0
|
1月前
|
数据采集 Python
如何在Python中使用Pandas库进行数据清洗?
Pandas在Python中提供高效的数据清洗功能,包括处理缺失值(`dropna()`删除、`fillna()`填充)、重复值(`duplicated()`检查、`drop_duplicates()`删除)、异常值(条件筛选、分位数、标准差)和文本数据(字符串操作、正则表达式)。这些方法帮助用户根据需求清洗数据,确保数据质量。
25 0
|
5天前
|
索引 Python
如何在Python中使用Pandas库进行季节性调整?
在Python中使用Pandas和Statsmodels进行季节性调整的步骤包括:导入pandas和seasonal_decompose模块,准备时间序列DataFrame,调用`seasonal_decompose()`函数分解数据为趋势、季节性和残差,可选地绘制图表分析,以及根据需求去除季节性影响(如将原始数据减去季节性成分)。这是对时间序列数据进行季节性分析的基础流程。
19 2
|
1月前
|
SQL 数据挖掘 数据处理
Python数据分析(二)—— Pandas快速入门
Python数据分析(二)—— Pandas快速入门