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

相关推荐
云泽野3 小时前
【Java|集合类】list遍历的6种方式
java·python·list
二进制person4 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6664 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way4 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
IMPYLH5 小时前
Python 的内置函数 reversed
笔记·python
.30-06Springfield5 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
永洪科技6 小时前
永洪科技荣获商业智能品牌影响力奖,全力打造”AI+决策”引擎
大数据·人工智能·科技·数据分析·数据可视化·bi
凌肖战7 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
小赖同学啊7 小时前
物联网数据安全区块链服务
开发语言·python·区块链
weixin_478689767 小时前
十大排序算法汇总
java·算法·排序算法