Python数据类型转换

数据类型的不一致可能导致分析错误,因此在数据清洗中通常需要对数据类型进行转换。

主要包括一下几个方面:

整数(int)和浮点数(float)之间的转换
字符串(str)和整数(int)之间的转换
字符串(str)和浮点数(float)之间的转换
布尔值(bool)和整数(int)之间的转换
复数(complex)和整数(int)或浮点数(float)之间的转换
日期和时间之间的转换等

对于以上数据类型转换,通常可以使用内置函数或类型转换运算符来实现数据类型转换:

python 复制代码
int(3.14)
# 返回3
float(3)
# 返回3.0
int('666')
# 返回666
str('0')
# 返回'0'
float('3.14')
# 返回3.14

举个例子:将字符串转换为浮点数,并保留两位小数,代码如下

python 复制代码
string = "3.14159" # 输入的字符串
number = float(string) # 将字符串转换为浮点数
result = round(number, 2) # 保留两位小数并进行四舍五入
print(result) # 打印结果

其他数据类型与布尔类型转换举例:

python 复制代码
# 将其他类型转换为布尔值
string_value = "Hello"
boolean_result1 = bool(string_value)  # True
print(boolean_result1)

list_value = []
boolean_result2 = bool(list_value)  # False
print(boolean_result2)

# 将布尔值转换为整数
true_value = True
integer_result1 = int(true_value)  # 1
print(integer_result1)

false_value = False
integer_result2 = int(false_value)  # 0
print(integer_result2)

# 输出结果为:
True
False
1
0

复数,整数及浮点数之间的转换举例:

python 复制代码
# 将整数转换为复数
num = 5
complex_num = complex(num)
print(complex_num) # (5+0j)

# 将浮点数转换为复数
num = 3.14
complex_num = complex(num)
print(complex_num) # (3.14+0j)

# 将复数转换为整数
complex_num = 7 + 8j
integer_part = int(complex_num.real)
print(integer_part) # 7

# 将复数转换为浮点数
complex_num = 9 - 6j
floating_point_part = float(complex_num.real)
print(floating_point_part) # 9.0

日期和时间的转换 使用内置模块datetime来转换:

python 复制代码
# 1. 将字符串类型的日期或时间转换为datetime对象:
from datetime import datetime
date_str = "2024-01-08"
time_str = "14:30:00"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
time_obj = datetime.strptime(time_str, "%H:%M:%S")
print("Date Object:", date_obj)
print("Time Object:", time_obj)

输出结果为:

Date Object: 2024-01-08 00:00:00

Time Object: 1900-01-01 14:30:00

python 复制代码
# 2.将datetime对象格式化成指定的字符串形式:
formatted_date = date_obj.strftime("%Y年%m月%d日")
formatted_time = time_obj.strftime("%H点%M分%S秒")
print("Formatted Date:", formatted_date)
print("Formatted Time:", formatted_time)

输出结果为:

Formatted Date: 2024年01月08日

Formatted Time: 14点30分00秒

对于Excel表格中的数据,可以使用Python的pandas库来读取和处理数据:

python 复制代码
# 以下是将Excel表格中的数据转换为指定数据类型的示例代码:
import pandas as pd    
# 读取Excel表格数据  
df = pd.read_excel('input.xlsx')    
# 将列A的数据类型转换为整数  
df['A'] = df['A'].astype(int)    
# 将列B的数据类型转换为浮点数  
df['B'] = df['B'].astype(float)    
# 将列C中的字符串转换为日期格式  
df['C'] = pd.to_datetime(df['C'])    
# 将列D中的字符串转换为布尔类型  
df['D'] = df['D'].astype(bool)    
# 将数据写入新的Excel文件  
df.to_excel('output.xlsx', index=False)

在这个示例中,我们首先使用pd.read_excel()方法读取Excel表格数据,并将其存储在df变量中。然后,我们使用astype()方法将列A和列B的数据类型转换为整数和浮点数。对于列C,我们使用pd.to_datetime()方法将其转换为日期格式。对于列D,我们使用astype(bool)将其转换为布尔类型。最后,我们使用to_excel()方法将处理后的数据写入新的Excel文件。请注意,index=False参数用于避免将索引列写入输出文件中。

相关推荐
xie_pin_an7 分钟前
C 语言排序算法全解析:从原理到实战,附性能对比
c语言·算法·排序算法
十六年开源服务商8 分钟前
怎样做好WordPress网站数据分析与运维服务
运维·数据挖掘·数据分析
CoovallyAIHub9 分钟前
SAM 真的开始「分割一切」,从图像到声音,Meta 开源 SAM Audio
深度学习·算法·计算机视觉
三斗米12 分钟前
从思维链到思维树:一步步解锁大语言模型的推理能力
算法
Hi~晴天大圣16 分钟前
if 变量和if not 变量用法之布尔真假值规则
python·if
老歌老听老掉牙17 分钟前
Vericut 5轴机床MCH文件解析与构建指南
xml·python·vericut
沃达德软件25 分钟前
大数据治安防控中心
大数据·人工智能·信息可视化·数据挖掘·数据分析
前端小L25 分钟前
贪心算法专题(二):波动中的智慧——只取极值「摆动序列」
数据结构·算法·贪心算法
aini_lovee26 分钟前
基于Jousselme距离改进D-S证据理论matlab实现
开发语言·算法·matlab
白兰地空瓶35 分钟前
你以为树只是画图?不——它是算法面试的“隐形主角”
前端·javascript·算法