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参数用于避免将索引列写入输出文件中。

相关推荐
MATLAB代码顾问5 小时前
5大智能算法优化标准测试函数对比(Python实现)
开发语言·python
ting94520005 小时前
Tornado 全栈技术深度指南:从原理到实战
人工智能·python·架构·tornado
果汁华5 小时前
Browserbase Skills:让 Claude Agent 真正“看见“网页世界
人工智能·python
ZhengEnCi5 小时前
04-缩放点积注意力代码实现 💻
人工智能·python
DeepReinforce6 小时前
三、AI量化投资:使用akshare获取A股主板20260430所有的涨停股票
python·量化·akshare·龙头战法
段一凡-华北理工大学6 小时前
【高炉炼铁领域炉温监测、预警、调控智能体设计与应用】~系列文章08:多模态数据融合:让数据更聪明
人工智能·python·高炉炼铁·ai赋能·工业智能体·高炉炉温
万粉变现经纪人6 小时前
如何解决 pip install llama-cpp-python 报错 未安装 CMake/Ninja 或 CPU 不支持 AVX 问题
开发语言·python·开源·aigc·pip·ai写作·llama
其实防守也摸鱼7 小时前
CTF密码学综合教学指南--第五章
开发语言·网络·笔记·python·安全·网络安全·密码学
MediaTea7 小时前
AI 术语通俗词典:C4.5 算法
人工智能·算法
Navigator_Z7 小时前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode