Python 小抄

news2024/9/21 0:34:17

Python 备忘单

目录

1.语法和空格
2.注释
3.数字和运算
4.字符串处理
5.列表、元组和字典
6.JSON
7.循环
8.文件处理
9.函数
10.处理日期时间
11.NumPy
12.Pandas

要运行单元格,请按 Shift+Enter 或单击页面顶部的 Run(运行)。

1.语法和空格

Python 使用缩进空格来指示语句的级别。下面的单元格是一个示例,其中 ‘if’ 和 ‘else’ 处于同一级别,而 ‘print’ 由空格分隔到不同级别。相同级别的项目的间距应相同。

student_number = input("Enter your student number:")
if student_number != 0:
    print("Welcome student {}".format(student_number))
else:
    print("Try again!")
Enter your student number: 1


Welcome student 1

2.注释

在 Python 中,注释以井号 ‘# ’ 开头并延伸至该行的末尾。’# ’ 可以在行的开头或代码之后。

# 这是打印“hello world!”的代码

print("Hello world!") # 打印 hello world 语句
print("# 在本例中不是注释")
Hello world!
# 在本例中不是注释

3.数字和运算

与其他编程语言一样,有四种类型的数字:

  • int 表示的整数(例如 1、20、45、1000)
  • float 表示的浮点数(例如 1.25、20.35、1000.00)
  • 长整数
  • 复数(例如 x+2y,其中 x 是已知的)
运算结果
x+yx 与 y 的和
x - yx 与 y 的差
x * yx 与 y 的乘积
x / yx 和 y 的商
x // yx 和 y 的商(取整)
x % yx / y 的余数
abs(x)x 的绝对值
int(x)将 x 转换为整数
long(x)将 x 转换为长整数
float(x)将 x 转换为浮点
pow(x, y)x 的 y 次方
x ** yx 的 y 次方
# 数字示例
a = 5 + 8
print("Sum of int numbers: {} and number format is {}".format(a, type(a)))

b = 5 + 2.3
print ("Sum of int and {} and number format is {}".format(b, type(b)))
Sum of int numbers: 13 and number format is <class 'int'>
Sum of int and 7.3 and number format is <class 'float'>

4.字符串处理

与其他编程语言一样,Python 具有丰富的字符串处理功能。

# 将字符串存储在变量中
test_word = "hello world to everyone"

# 打印 test_word 值
print(test_word)

# 使用 [] 访问字符串的字符。第一个字符由 '0' 表示。
print(test_word[0])

# 使用 len() 函数查找字符串的长度
print(len(test_word))

# 在字符串中查找的一些示例
print(test_word.count('l')) # 计算 l 在字符串中重复出现的次数
print(test_word.find("o")) # 在字符串中查找字母 'o'。返回第一个匹配项的位置。
print(test_word.count(' ')) # 计算字符串中的空格数
print(test_word.upper()) # 将字符串更改为大写
print(test_word.lower()) # 将字符串更改为小写
print(test_word.replace("everyone","you")) # 将单词“everyone”替换为“you”
print(test_word.title()) # 将字符串更改为标题格式
print(test_word + "!!!") # 连结字符串
print(":".join(test_word)) # 在每个字符之间添加“:”
print("".join(reversed(test_word))) # 将字符串进行反转 
hello world to everyone
h
23
3
4
3
HELLO WORLD TO EVERYONE
hello world to everyone
hello world to you
Hello World To Everyone
hello world to everyone!!!
h:e:l:l:o: :w:o:r:l:d: :t:o: :e:v:e:r:y:o:n:e
enoyreve ot dlrow olleh

5.列表、元组和字典

Python 支持数据类型列表、元组、字典和数组。

列表

通过将所有项目(元素)放在方括号 [ ] 内并以逗号分隔来创建列表。列表可以具有任意数量的项目,并且它们可以具有不同的类型(整数、浮点数、字符串等)。

# Python 列表类似于数组。您也可以创建空列表。

my_list = []

first_list = [3, 5, 7, 10]
second_list = [1, 'python', 3]
# 嵌套多个列表
nested_list = [first_list, second_list]
nested_list
[[3, 5, 7, 10], [1, 'python', 3]]
# 合并多个列表
combined_list = first_list + second_list
combined_list
[3, 5, 7, 10, 1, 'python', 3]
# 您可以像分割字符串一样分割列表
combined_list[0:3]
[3, 5, 7]
# 将新条目追加到列表
combined_list.append(600)
combined_list
[3, 5, 7, 10, 1, 'python', 3, 600]
# 从列表中删除最后一个条目
combined_list.pop()
600
# 迭代列表
for item in combined_list:
    print(item)    
3
5
7
10
1
python
3

元组

元组类似于列表,但是您可以将其与括号 ( ) 一起使用,而不是与方括号一起使用。主要区别在于元组不可变,而列表可变。

my_tuple = (1, 2, 3, 4, 5)
my_tuple[1:4]
(2, 3, 4)

字典

字典也称为关联数组。字典由键值对的集合组成。每个键值对将键映射到其关联值。

desk_location = {'jack': 123, 'joe': 234, 'hary': 543}
desk_location['jack']
123

6.JSON

JSON 是用 JavaScript 对象表示法编写的文本。Python 有一个名为 json 的内置程序包,可用于处理 JSON 数据。

import json

# 示例 JSON 数据
x = '{"first_name":"Jane", "last_name":"Doe", "age":25, "city":"Chicago"}'

# 读取 JSON 数据
y = json.loads(x)

# 打印输出结果,类似于字典
print("Employee name is "+ y["first_name"] + " " + y["last_name"])
Employee name is Jane Doe

7.循环

If, Else, ElIf 循环:和其他任何编程语言一样,Python 支持条件语句。Python 依靠缩进(行的开头是空格)来定义代码范围。

a = 22
b = 33
c = 100

# if ... else 示例
if a > b:
    print("a is greater than b")
else:
    print("b is greater than a")
    
    
# if .. else .. elif 示例

if a > b:
    print("a is greater than b")
elif b > c:
    print("b is greater than c")
else:
    print("b is greater than a and c is greater than b")
b is greater than a
b is greater than a and c is greater than b

While 循环:只要条件为 true,就执行一组语句

# while 示例
i = 1
while i < 10:
    print("count is " + str(i))
    i += 1

print("="*10)

# 如果 x 为 2,则继续进行下一个迭代。最后,条件为 false 时打印消息。

x = 0
while x < 5:
    x += 1
    if x == 2:
        continue
    print(x)
else:
    print("x is no longer less than 5")
count is 1
count is 2
count is 3
count is 4
count is 5
count is 6
count is 7
count is 8
count is 9
==========
1
3
4
5
x is no longer less than 5

For 循环: For 循环更像 Python 中的迭代器。For 循环用于遍历序列(列表、元组、字典、集合、字符串或范围)。

# 循环示例
fruits = ["orange", "banana", "apple", "grape", "cherry"]
for fruit in fruits:
    print(fruit)

print("\n")
print("="*10)
print("\n")

# 迭代范围
for x in range(1, 10, 2):
    print(x)
else:
    print("task complete")

print("\n")
print("="*10)
print("\n")

# 迭代多个列表
traffic_lights = ["red", "yellow", "green"]
action = ["stop", "slow down", "go"]

for light in traffic_lights:
    for task in action:
        print(light, task)
orange
banana
apple
grape
cherry

==========

1
3
5
7
9
task complete

==========

red stop
red slow down
red go
yellow stop
yellow slow down
yellow go
green stop
green slow down
green go

8.文件处理

在 Python 中处理文件的主要函数是 open() 函数。open() 函数使用两个参数:filename 和 mode。

打开文件有四种不同的方法(模式):

  • “r” - 读取
  • “a” - 追加
  • “w” - 写入
  • “x” - 创建

此外,您还可以指定是以二进制还是文本模式处理文件。

  • “t” - 文本
  • “b” - 二进制
# 我们来创建一个测试文本文件
!echo "This is a test file with text in it.This is the first line." > test.txt
!echo "This is the second line." >> test.txt
!echo "This is the third line." >> test.txt
# 读取文件
file = open('test.txt', 'r')
print(file.read())
file.close()

print("\n")
print("="*10)
print("\n")

# 读取文件的前 10 个字符
file = open('test.txt', 'r')
print(file.read(10))
file.close()

print("\n")
print("="*10)
print("\n")

# 从文件中读取行

file = open('test.txt', 'r')
print(file.readline())
file.close()
This is a test file with text in it.This is the first line.
This is the second line.
This is the third line.


==========

This is a 

==========

This is a test file with text in it.This is the first line.
# 创建新文件

file = open('test2.txt', 'w')
file.write("This is content in the new test2 file.")
file.close()

# 读取新文件的内容
file = open('test2.txt', 'r')
print(file.read())
file.close()
This is content in the new test2 file.
# 更新文件
file = open('test2.txt', 'a')
file.write("\nThis is additional content in the new file.")
file.close()

# 读取新文件的内容
file = open('test2.txt', 'r')
print(file.read())
file.close()
This is content in the new test2 file.
This is additional content in the new file.
# 删除文件
import os
file_names = ["test.txt", "test2.txt"]
for item in file_names:
    if os.path.exists(item):
        os.remove(item)
        print(f"File {item} removed successfully!")
    else:
        print(f"{item} file does not exist.")
File test.txt removed successfully!
File test2.txt removed successfully!

9.函数

函数是在调用时运行的代码块。您可以将数据或 参数 传递到函数中。在 Python 中,函数是由 def 定义的。

# 定义函数
def new_funct():
    print("A simple function")

# 调用函数
new_funct()
A simple function
# 带有参数的示例函数

def param_funct(first_name):
    print(f"Employee name is {first_name}.")

param_funct("Harry")
param_funct("Larry")
param_funct("Shally")
Employee name is Harry.
Employee name is Larry.
Employee name is Shally.

匿名函数 (lambda):lambda 是一个小的匿名函数。Lambda 函数可以使用任意数量的参数,但只有一个表达式。

# lambda 示例
x = lambda y: y + 100
print(x(15))

print("\n")
print("="*10)
print("\n")

x = lambda a, b: a*b/100
print(x(2,4))
115

==========

0.08

10.处理日期时间

Python 中的 datetime 模块可用于处理日期对象。

import datetime

x = datetime.datetime.now()

print(x)
print(x.year)
print(x.strftime("%A"))
print(x.strftime("%B"))
print(x.strftime("%d"))
print(x.strftime("%H:%M:%S %p"))
2024-05-15 12:42:35.994638
2024
Wednesday
May
15
12:42:35 PM

11.NumPy

NumPy 是使用 Python 进行科学计算的基本软件包。以下是它包含的一部分内容:

  • 强大的 N 维数组对象
  • 复杂的(广播)函数
  • 集成 C/C++ 和 Fortran 代码的工具
  • 有用的线性代数、傅立叶变换和随机数功能
# 使用 pip 安装 NumPy
!pip install numpy
Requirement already satisfied: numpy in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (1.22.4)
# 导入 NumPy 模块
import numpy as np

检查您的数组

# 创建数组
a = np.arange(15).reshape(3, 5) # 在 3 x 5 维中创建范围为 0-14 的数组
b = np.zeros((3,5)) # 使用 0 创建数组
c = np.ones( (2,3,4), dtype=np.int16 ) # 使用 1 创建数组并定义数据类型
d = np.ones((3,5))
a.shape # 数组维度
(3, 5)
len(b)# 数组长度
3
c.ndim # 数组维度的数量
3
a.size # 数组元素的数量
15
b.dtype # 数组元素的数据类型
dtype('float64')
c.dtype.name # 数据类型的名称
'int16'
c.astype(float) # 将数组类型转换为其他类型
array([[[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]]])

基本数学运算

# 创建数组
a = np.arange(15).reshape(3, 5) # 在 3 x 5 维中创建范围为 0-14 的数组
b = np.zeros((3,5)) # 使用 0 创建数组
c = np.ones( (2,3,4), dtype=np.int16 ) # 使用 1 创建数组并定义数据类型
d = np.ones((3,5))
np.add(a,b) # 加法
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.]])
np.subtract(a,b) # 减法
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.]])
np.divide(a,d) # 除法
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.]])
np.multiply(a,d) # 乘法
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.]])
np.array_equal(a,b) # 对比 - 数组方式
False

聚合函数

# 创建数组
a = np.arange(15).reshape(3, 5) # 在 3 x 5 维中创建范围为 0-14 的数组
b = np.zeros((3,5)) # 使用 0 创建数组
c = np.ones( (2,3,4), dtype=np.int16 ) # 使用 1 创建数组并定义数据类型
d = np.ones((3,5))
a.sum() # 按数组求和
105
a.min() # 数组最小值
0
a.mean() # 数组平均值
7.0
a.max(axis=0) # 数组行的最大值
array([10, 11, 12, 13, 14])
np.std(a) # 标准差
4.320493798938574

子集、切片和索引

# 创建数组
a = np.arange(15).reshape(3, 5) # 在 3 x 5 维中创建范围为 0-14 的数组
b = np.zeros((3,5)) # 使用 0 创建数组
c = np.ones( (2,3,4), dtype=np.int16 ) # 使用 1 创建数组并定义数据类型
d = np.ones((3,5))
a[1,2] # 选择第 1 行、第 2 列的元素
7
a[0:2] # 选择索引 0 和 1 上的项目
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
a[:1] # 选择第 0 行的所有项目
array([[0, 1, 2, 3, 4]])
a[-1:] # 选择最后一行的所有项目
array([[10, 11, 12, 13, 14]])
a[a<2] # 从 'a' 中选择小于 2 的元素
array([0, 1])

数组处理

# 创建数组
a = np.arange(15).reshape(3, 5) # 在 3 x 5 维中创建范围为 0-14 的数组
b = np.zeros((3,5)) # 使用 0 创建数组
c = np.ones( (2,3,4), dtype=np.int16 ) # 使用 1 创建数组并定义数据类型
d = np.ones((3,5))
np.transpose(a) # 转置数组 'a'
array([[ 0,  5, 10],
       [ 1,  6, 11],
       [ 2,  7, 12],
       [ 3,  8, 13],
       [ 4,  9, 14]])
a.ravel() # 展平数组
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14])
a.reshape(5,-2) # 重整但不更改数据
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11],
       [12, 13, 14]])
np.append(a,b) # 将项目追加到数组
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12.,
       13., 14.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.])
np.concatenate((a,d), axis=0) # 连结数组
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.],
       [10., 11., 12., 13., 14.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.,  1.]])
np.vsplit(a,3) # 在第 3 个索引处垂直拆分数组
[array([[0, 1, 2, 3, 4]]),
 array([[5, 6, 7, 8, 9]]),
 array([[10, 11, 12, 13, 14]])]
np.hsplit(a,5) # 在第 5 个索引处水平拆分数组
[array([[ 0],
        [ 5],
        [10]]),
 array([[ 1],
        [ 6],
        [11]]),
 array([[ 2],
        [ 7],
        [12]]),
 array([[ 3],
        [ 8],
        [13]]),
 array([[ 4],
        [ 9],
        [14]])]

Pandas

Pandas 是 BSD 许可的开源代码库,为 Python 编程语言提供了高性能、易于使用的数据结构和数据分析工具。

Pandas DataFrame 是 Python 中复杂数据集合在内存中使用最广泛的表示形式。

# 使用 pip 安装 pandas、xlrd 和 openpyxl
!pip install pandas
!pip install xlrd openpyxl
Requirement already satisfied: pandas in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (2.2.1)
Requirement already satisfied: numpy<2,>=1.22.4 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from pandas) (1.22.4)
Requirement already satisfied: python-dateutil>=2.8.2 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from pandas) (2.9.0)
Requirement already satisfied: pytz>=2020.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from pandas) (2024.1)
Requirement already satisfied: tzdata>=2022.7 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from pandas) (2024.1)
Requirement already satisfied: six>=1.5 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)
Collecting xlrd
  Downloading xlrd-2.0.1-py2.py3-none-any.whl.metadata (3.4 kB)
Requirement already satisfied: openpyxl in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (3.1.2)
Requirement already satisfied: et-xmlfile in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from openpyxl) (1.1.0)
Downloading xlrd-2.0.1-py2.py3-none-any.whl (96 kB)
[2K   [90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━[0m [32m96.5/96.5 kB[0m [31m11.2 MB/s[0m eta [36m0:00:00[0m
[?25hInstalling collected packages: xlrd
Successfully installed xlrd-2.0.1
# 导入 NumPy 和 Pandas 模块
import numpy as np
import pandas as pd
# 示例 dataframe df
df = pd.DataFrame({'num_legs': [2, 4, np.nan, 0],
                   'num_wings': [2, 0, 0, 0],
                   'num_specimen_seen': [10, np.nan, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])
df # 显示 dataframe df
num_legsnum_wingsnum_specimen_seen
falcon2.0210.0
dog4.00NaN
spiderNaN01.0
fish0.008.0
# 另一个示例 dataframe df1 - 使用带有日期时间索引和标记列的 NumPy 数组
df1 = pd.date_range('20130101', periods=6)
df1 = pd.DataFrame(np.random.randn(6, 4), index=df1, columns=list('ABCD'))
df1 # 显示 dataframe df1
ABCD
2013-01-010.4550052.0472800.260058-1.068430
2013-01-02-1.9038300.5212490.9067782.358446
2013-01-030.0362780.237705-0.836402-0.142862
2013-01-041.3021992.130269-0.467286-0.739326
2013-01-050.9240340.4136901.122296-1.917679
2013-01-06-1.4280251.2772790.1646011.313498

查看数据

df1 = pd.date_range('20130101', periods=6)
df1 = pd.DataFrame(np.random.randn(6, 4), index=df1, columns=list('ABCD'))
df1.head(2) # 查看顶部数据
ABCD
2013-01-010.9101310.8570311.3243970.768240
2013-01-02-1.1937120.598527-0.654860-1.528201
df1.tail(2) # 查看底部数据
ABCD
2013-01-051.009387-0.695923-1.2542390.374314
2013-01-06-0.6226980.9595860.3512941.240811
df1.index # 显示索引列
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
               '2013-01-05', '2013-01-06'],
              dtype='datetime64[ns]', freq='D')
df1.dtypes # 检查数据类型
A    float64
B    float64
C    float64
D    float64
dtype: object
df1.describe() # 显示数据的快速统计摘要
ABCD
count6.0000006.0000006.0000006.000000
mean-0.4321930.637821-0.1580000.080423
std1.1517990.7699160.9053030.973543
min-1.827255-0.695923-1.254239-1.528201
25%-1.1125370.500875-0.639878-0.299781
50%-0.7458560.727779-0.3572960.207468
75%0.5269240.9339480.2335540.669758
max1.0093871.6393821.3243971.240811

子集、切片和索引

df1 = pd.date_range('20130101', periods=6)
df1 = pd.DataFrame(np.random.randn(6, 4), index=df1, columns=list('ABCD'))
df1.T # 置换数据
2013-01-012013-01-022013-01-032013-01-042013-01-052013-01-06
A0.339706-0.033353-0.4699120.683896-0.119535-0.391874
B-1.2711341.1608610.594625-0.355716-1.718980-1.546150
C0.6312700.5258600.173641-1.885387-2.915834-0.781985
D0.674431-0.2748300.6303071.1326420.0216961.299410
df1.sort_index(axis=1, ascending=False) # 按轴排序
DCBA
2013-01-010.6744310.631270-1.2711340.339706
2013-01-02-0.2748300.5258601.160861-0.033353
2013-01-030.6303070.1736410.594625-0.469912
2013-01-041.132642-1.885387-0.3557160.683896
2013-01-050.021696-2.915834-1.718980-0.119535
2013-01-061.299410-0.781985-1.546150-0.391874
df1.sort_values(by='B') # 按值排序
ABCD
2013-01-05-0.119535-1.718980-2.9158340.021696
2013-01-06-0.391874-1.546150-0.7819851.299410
2013-01-010.339706-1.2711340.6312700.674431
2013-01-040.683896-0.355716-1.8853871.132642
2013-01-03-0.4699120.5946250.1736410.630307
2013-01-02-0.0333531.1608610.525860-0.274830
df1['A'] # 选择列 A
2013-01-01    0.339706
2013-01-02   -0.033353
2013-01-03   -0.469912
2013-01-04    0.683896
2013-01-05   -0.119535
2013-01-06   -0.391874
Freq: D, Name: A, dtype: float64
df1[0:3] # 选择索引 0 到 2
ABCD
2013-01-010.339706-1.2711340.6312700.674431
2013-01-02-0.0333531.1608610.525860-0.274830
2013-01-03-0.4699120.5946250.1736410.630307
df1['20130102':'20130104'] # 从匹配值的索引中选择
ABCD
2013-01-02-0.0333531.1608610.525860-0.274830
2013-01-03-0.4699120.5946250.1736410.630307
2013-01-040.683896-0.355716-1.8853871.132642
df1.loc[:, ['A', 'B']] # 通过标签在多轴上选择
AB
2013-01-010.339706-1.271134
2013-01-02-0.0333531.160861
2013-01-03-0.4699120.594625
2013-01-040.683896-0.355716
2013-01-05-0.119535-1.718980
2013-01-06-0.391874-1.546150
df1.iloc[3] # 通过传递的整数的位置进行选择
A    0.683896
B   -0.355716
C   -1.885387
D    1.132642
Name: 2013-01-04 00:00:00, dtype: float64
df1[df1 > 0] # 从满足布尔运算条件的 DataFrame 中选择值
ABCD
2013-01-010.339706NaN0.6312700.674431
2013-01-02NaN1.1608610.525860NaN
2013-01-03NaN0.5946250.1736410.630307
2013-01-040.683896NaNNaN1.132642
2013-01-05NaNNaNNaN0.021696
2013-01-06NaNNaNNaN1.299410
df2 = df1.copy() # 将 df1 数据集复制到 df2
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three'] # 添加带有值的 E 列
df2[df2['E'].isin(['two', 'four'])] # 使用 isin 方法进行筛选
ABCDE
2013-01-03-0.4699120.5946250.1736410.630307two
2013-01-05-0.119535-1.718980-2.9158340.021696four

数据缺失

Pandas 主要使用值 np.nan 来表示缺失数据。默认情况下,它不包括在计算中。

df = pd.DataFrame({'num_legs': [2, 4, np.nan, 0],
                   'num_wings': [2, 0, 0, 0],
                   'num_specimen_seen': [10, np.nan, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])
df.dropna(how='any') # 删除所有缺失数据的行
num_legsnum_wingsnum_specimen_seen
falcon2.0210.0
fish0.008.0
df.dropna(how='any', axis=1) # 删除所有缺失数据的列
num_wings
falcon2
dog0
spider0
fish0
df.fillna(value=5) # 用值 5 填充缺失的数据
num_legsnum_wingsnum_specimen_seen
falcon2.0210.0
dog4.005.0
spider5.001.0
fish0.008.0
pd.isna(df) # 在缺失数据的位置获取布尔掩码
num_legsnum_wingsnum_specimen_seen
falconFalseFalseFalse
dogFalseFalseTrue
spiderTrueFalseFalse
fishFalseFalseFalse

文件处理

df = pd.DataFrame({'num_legs': [2, 4, np.nan, 0],
                   'num_wings': [2, 0, 0, 0],
                   'num_specimen_seen': [10, np.nan, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])
df.to_csv('foo.csv') # 写入 CSV 文件
pd.read_csv('foo.csv') # 从 CSV 文件中读取
Unnamed: 0num_legsnum_wingsnum_specimen_seen
0falcon2.0210.0
1dog4.00NaN
2spiderNaN01.0
3fish0.008.0
df.to_excel('foo.xlsx', sheet_name='Sheet1') # 写入 Microsoft Excel 文件
pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) # 从 Microsoft Excel 文件中读取
Unnamed: 0num_legsnum_wingsnum_specimen_seen
0falcon2.0210.0
1dog4.00NaN
2spiderNaN01.0
3fish0.008.0

绘图

# 使用 pip 安装 Matplotlib
!pip install matplotlib
Requirement already satisfied: matplotlib in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (3.8.3)
Requirement already satisfied: contourpy>=1.0.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (1.2.0)
Requirement already satisfied: cycler>=0.10 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (0.12.1)
Requirement already satisfied: fonttools>=4.22.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (4.50.0)
Requirement already satisfied: kiwisolver>=1.3.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (1.4.5)
Requirement already satisfied: numpy<2,>=1.21 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (1.22.4)
Requirement already satisfied: packaging>=20.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (21.3)
Requirement already satisfied: pillow>=8 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (10.2.0)
Requirement already satisfied: pyparsing>=2.3.1 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (3.1.2)
Requirement already satisfied: python-dateutil>=2.7 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from matplotlib) (2.9.0)
Requirement already satisfied: six>=1.5 in /home/ec2-user/anaconda3/envs/python3/lib/python3.10/site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)
from matplotlib import pyplot as plt # 导入 Matplotlib 模块
# 生成随机时间序列数据
ts = pd.Series(np.random.randn(1000),index=pd.date_range('1/1/2000', periods=1000)) 
ts.head()
2000-01-01    0.273730
2000-01-02    0.934832
2000-01-03   -0.142245
2000-01-04   -0.499136
2000-01-05    0.169899
Freq: D, dtype: float64
ts = ts.cumsum()
ts.plot() # 绘制图表
plt.show()


请添加图片描述

# 在 DataFrame 上,plot() 方法可以方便绘制带有标签的所有列
df4 = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,columns=['A', 'B', 'C', 'D'])
df4 = df4.cumsum()
df4.head()
ABCD
2000-01-01-0.8477551.239531-0.7608560.668182
2000-01-02-1.1910671.930612-2.5876670.075473
2000-01-03-1.3537041.815771-1.788468-2.039681
2000-01-04-2.3381591.734058-2.269514-0.756332
2000-01-05-2.8355702.067088-3.3963661.352672
df4.plot()
plt.show()


请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1679234.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

「每日跟读」英语常用句型公式 第15篇

「每日跟读」英语常用句型公式 第15篇 1. It’s only logical that __ 合理的做法/结论是__ It’s only logical that we should take a break &#xff08;合理的做法是我们应该休息一下&#xff09; It’s only logical that we work hard to make money&#xff08;合理…

如何设计知识竞赛活动中的观众互动环节

知识竞赛活动过程中有多种方式进行观众互动&#xff0c;达到台上台下互动的效果&#xff0c;让台下观众参与到竞赛活动中&#xff0c;增加现场气氛。下面介绍几种常用观众互动环节设计方法。 一、台上选手对抗台下观众 此方案为台下观众和台上选手一起答题&#xff0c;如果台…

又双叒叕新增2本SCI期刊“On Hold“,慎投,有剔除风险!

本周投稿推荐 SSCI • 2区社科经管类&#xff0c;3.0-4.0&#xff08;录用友好&#xff09; EI • 计算机工程生物医学等&#xff08;领域广&#xff0c;录用极快&#xff09; CNKI • 3天内初审录用&#xff0c;随即出版&#xff08;急录友好&#xff09; SCI&EI …

[Bootloader][uboot]code总结

文章目录 1、U_BOOT_DRIVER2、DM框架dm_scan_platdatadm_extended_scan_fdt 1、U_BOOT_DRIVER 使用这个宏可以定义一个驱动实例&#xff0c;宏定义是 其中使用的struct driver结构体 使用的ll_entry_declare宏定义是 归结为 2、DM框架 1、 DM框架 DM模型抽象出了以下四个…

测试之路 - 精准而优雅

引子 这几年业内一直在做精准测试&#xff0c;大都使用工具 diff 代码改动、分析代码覆盖率这些平台集成的能力。 业务测试中&#xff0c;我们在技术设计和代码实现的基础上也做了一些精减和精准的测试实践&#xff0c;通过深入测试有针对的设计 case&#xff0c;发现隐藏问题…

智游剪辑1.5.0发布!

智游剪辑1.5.0发布了&#xff0c;快来看看更新了啥功能吧&#xff01; 主页卡片升级 现在功能卡片新增图标&#xff0c;比以前更好看更直观 我的收藏 遇到自己喜欢的功能直接点击收藏就可以了&#xff0c;后面我们就能快速找到这个功能 批量ncm转mp3功能 目前看后台有很多人…

STC8增强型单片机开发【热敏电阻】

目录 一、引言 二、热敏电阻概述 三、STC8增强型单片机简介 四、基于STC8单片机的热敏电阻测温系统 五、热敏电阻测温系统的优化与扩展 提高测量精度 扩展系统功能 六、 温度计算步骤 通过ADC采样计算出热敏电阻位置的电压 通过欧姆定律计算热敏电阻的阻值 通过阻值…

Java微信小程序订阅消息提醒的实现与对接

文章目录 一、准备工作1. 注册微信小程序&#xff0c;并开通订阅消息功能。2. 获取小程序的AppID和AppSecret。3. 在微信小程序管理后台&#xff0c;设置提醒模板&#xff0c;并获取模板ID。4. 小程序端需要获取用户订阅允许提醒的权限&#xff08;1&#xff09;引导用户触发订…

win11快速安装mysql数据库系统

win11快速安装mysql数据库系统 1、下载 1.1 打开官网 1.2 向下滚动页面 1.3 进入下载选项 1.4 下载8.0.4 LTS 1.5 开始下载 1.6 下载中 2、解压 大家注意&#xff0c;此时解压后目录是没有data目录的。 3、数据库初始化 3.1 管理员身份打开CMD 开始菜单上&#xff0c;输入…

【找到所有数组中消失的数字】leetcode,python

很菜的写法&#xff1a; class Solution:def findDisappearedNumbers(self, nums: List[int]) -> List[int]:nlen(nums)#存1-Nnum_1[i for i in range(1,n1)]#预存数num_2[]nums.sort()for i in nums:num_1[i-1]0for i in num_1:if i!0:num_2.append(i)return num_2能过但是…

link.click()时浏览器报错The file at ‘data:image/png;base64,iVBORw

代码如下&#xff1a; const dataURL canvas.toDataURL({format: "png",width: 400,height: 400, });const link document.createElement("a"); link.download new Date().getTime();link.href dataURL; document.body.appendChild(link); link.click…

webpack优化构建速度示例-合理配置loader的include exclude:

实际上&#xff0c;babel-loader 在 Webpack 配置中默认并不包含 exclude 和 include 选项的默认值&#xff0c;通常&#xff0c;为了优化构建性能&#xff0c;开发者会显式地设置 exclude 和 include 选项&#xff0c;以便 babel-loader 只处理必要的文件。 src/index.js impo…

【漏洞复现】Secnet-智能路由系统弱口令

0x01 产品简介 Secnet安网智能AC管理系统是广州安网通信技术有限公司(简称“安网通信”)的无线AP管理系统 0x02 漏洞描述 攻击者可直接利用弱口令登录系统 0x03 搜索语法 fofa: title"安网-智能路由系统" || title"智能路由系统" || title"安网科…

做海外问卷调查有什么方法技巧?

大家好&#xff0c;我是橙河老师&#xff0c;很久没更新文章了&#xff0c;一方面是比较忙&#xff0c;另一方面是觉得关于项目介绍的文章&#xff0c;写的也差不多了。 后面的文章&#xff0c;还是着重讲解不同渠道的特点、做题技巧、人设创建这些实战性的内容。 我不像其他公…

有什么操作简单的副业或兼职呢?

以下是操作简单的副业或兼职 1. 网络兼职 可以在网上找一些兼职工作&#xff0c;如网络营销、客服、文案撰写等&#xff0c;只需要有一台电脑和网络连接即可。 2. 手机任务 可以用手机做做致米宝库的任务&#xff0c;一天有一百多块钱&#xff0c;还可以电脑学习项目资源&am…

PCIE协议-2-事务层规范-Virtual Channel (VC) Mechanism

2.5 虚拟通道&#xff08;VC&#xff09;机制 虚拟通道&#xff08;VC&#xff09;机制提供了对可以在整个结构中传输使用TC&#xff08;流量类别&#xff09;标签区分的流量的支持。VC的基础是独立的结构资源&#xff08;队列/缓冲区及其相关的控制逻辑&#xff09;。这些资源…

异步I/O库-libuv介绍

1.简介 libuv是一个跨平台的支持事件驱动的异步I/O的库&#xff0c;使开发者可以以非阻塞的方式执行文件I/O操作、网络通信、子进程管理等。 libuv的主要特点包括&#xff1a; 事件循环&#xff1a;libuv有一个基于事件循环的模型&#xff0c;它不断地轮询事件&#xff0c;并…

VC++ 6.0开发文件重复整理工具开发

开发背景&#xff1a;手机上的文件越来越多&#xff0c;想要备份下文件结果文件太多杂乱无章且重复文件冗余存储造成存储空间滥发&#xff0c;所以决定开发一个小工具来整理重复文件。由于本人电脑运行慢&#xff0c;选择VC6.0作为开发IDE&#xff0c;操作虽然麻烦点&#xff0…

【记录】docker笔记(五):Docker网络-Network Namespace

Docker 网络理论基础 要了解docker网络&#xff0c;先了解如下基础概念。 Network Namespace Docker 网络的底层原理是 Linux 的 Network Namespace &#xff0c;所以对于 Linux Network Namespace 的理解对 Docker 网络底层原理的理解非常重要。 简介 Network Name…

java技术:nacos

目录 一、docker安装 1、创建一个nacos 2、复制配置信息出来&#xff08;方便修改配置文件&#xff09; 3、删除nacos 4、修改配置文件&#xff08;主要是一下几个&#xff09; 6、创建数据库 nacos 7、重启nacos mysql 一、docker安装 1、创建一个nacos docker run …