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

相关推荐
破无差10 分钟前
python实现简单的地图绘制与标记20250705
python
向阳@向远方11 分钟前
第二章 简单程序设计
开发语言·c++·算法
喜欢吃豆32 分钟前
目前最火的agent方向-A2A快速实战构建(二): AutoGen模型集成指南:从OpenAI到本地部署的全场景LLM解决方案
后端·python·深度学习·flask·大模型
好开心啊没烦恼1 小时前
Python 数据分析:DataFrame,生成,用字典创建 DataFrame ,键值对数量不一样怎么办?
开发语言·python·数据挖掘·数据分析
github_czy1 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
许愿与你永世安宁2 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子2 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
周树皮不皮2 小时前
20250704【翻转&二叉树】|Leetcodehot100之226【pass】&今天计划
python
魔芋红茶2 小时前
spring-initializer
python·学习·spring
喜欢吃豆2 小时前
快速手搓一个MCP服务指南(九): FastMCP 服务器组合技术:构建模块化AI应用的终极方案
服务器·人工智能·python·深度学习·大模型·github·fastmcp