提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
使用Python读取txt文本数据
提示:以下是本篇文章正文内容,下面案例可供参考
PP.txt文本
数据来源:调查报告
时间范围:2023.1.1~2023.12.1
year,month,day,gender,name,income
2023,2,2,男,小王,5&000
#2023,3,3,女,小林,6&000
2023,4,4,女,小张,18&000
来自公开调查数据
2023年4月
示例
import pandas as pd
# 读取 txt 文件
a = pd.read_csv("PP.txt", sep=',', skiprows=2, skipfooter=2, comment='#', thousands='&', engine='python')
# 将日期列合并为单个日期时间列,用 - 连接
a['birthday'] = a['year'].astype(str) + '-' + a['month'].astype(str) + '-' + a['day'].astype(str)
# 删除原始的年月日列
a = a.drop(columns=['year', 'month', 'day'])
a = a[['birthday', 'gender', 'name', 'income']]
print(a)
输出:
birthday gender name income
0 2023-02-02 男 小王 5000
1 2023-04-04 女 小张 18000
解析read_csv
首先引入Pandas模块中的read_csv
函数,他可以读取txt或者csv文本格式的数据。该函数中有一些重要参数。
首先"PP.txt"
是你所需要读取的文档,而sep
是用于指定分隔符,默认就是逗号;
如果设置了 skiprows=n
,则将跳过文件的前 n 行;skipfooter=n
,则将跳过文件的最后 n 行;
comment
参数用于指定在数据文件中表示注释的字符或字符串,在这里指定为 # ,当在数据文件中遇到 comment 参数指定的字符或字符串时,Pandas 将跳过该行。
当在数据文件中遇到 thousands
参数指定的字符时,Pandas 将忽略该字符,并将其从数字中去除。
engine
参数用于选择解析器引擎,以确定 Pandas 应如何读取数据文件。在 read_csv() 函数中,engine 参数的默认值是 “c”,表示使用 C 解析器引擎。C 解析器引擎速度较快,但在某些情况下可能不支持某些功能。另一个可选的解析器引擎是 “python”,它较为灵活,支持更多功能,例如支持 skipfooter 参数。因此,如果你需要使用 skipfooter 参数,则需要将 engine 参数设置为 “python”。
删除列和重新排序列
将年月日整合成birthday后,代码输出是这样的:
year month day gender name income birthday
0 2023 2 2 男 小王 5000 2023-2-2
1 2023 4 4 女 小张 18000 2023-4-4
这时候用a = a.drop(columns=['year', 'month', 'day'])
删除年月日:
gender name income birthday
0 男 小王 5000 2023-2-2
1 女 小张 18000 2023-4-4
如果我们想要将birthday放到最前面该怎么做呢?a = a[['birthday', 'gender', 'name', 'income']]
将列重新排序。得到最终结果:
birthday gender name income
0 2023-2-2 男 小王 5000
1 2023-4-4 女 小张 18000