Python数据类型转换

本文详细介绍了在IT技术中,如何在Python编程中进行不同类型的数据转换,包括整数、浮点数、字符串、布尔值、复数以及日期时间的转换,同时展示了如何使用pandas库处理Excel数据以确保分析的准确性。
摘要由CSDN通过智能技术生成

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

主要包括一下几个方面:

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

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

int(3.14)
# 返回3
float(3)
# 返回3.0
int('666')
# 返回666
str('0')
# 返回'0'
float('3.14')
# 返回3.14

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

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

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

# 将其他类型转换为布尔值
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

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

# 将整数转换为复数
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来转换:

# 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

# 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库来读取和处理数据:

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

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值