pandas读取txt文件
读取txt文件需要确定txt文件是否符合基本的格式,也就是是否存在\t
,,,
等特殊的分隔符
一般txt文件长成这个样子
txt文件举例
下面的文件为空格间隔
1 2019-03-22 00:06:24.4463094 中文测试
2 2019-03-22 00:06:32.4565680 需要编辑encoding
3 2019-03-22 00:06:32.6835965 ashshsh
4 2017-03-22 00:06:32.8041945 eggg
读取命令采用 read_csv或者 read_table都可以
import pandas as pd
df = pd.read_table("./test.txt")
print(df)
import pandas as pd
df = pd.read_csv("./test.txt")
print(df)
但是,注意,这个地方读取出来的数据内容为3行1列的DataFrame类型,并没有按照我们的要求得到3行4列
import pandas as pd
df = pd.read_csv("./test.txt")
print(type(df))
print(df.shape)
<class 'pandas.core.frame.DataFrame'>
(3, 1)
read_csv函数
默认: 从文件、URL、文件新对象中加载带有分隔符的数据,默认分隔符是逗号。
上述txt文档并没有逗号分隔,所以在读取的时候需要增加sep分隔符参数
df = pd.read_csv("./test.txt",sep=' ')
read_pickle函数
read_pickle is only guaranteed to be backwards compatible to pandas 0.20.3.
Examples
>>> original_df = pd.DataFrame({"foo": range(5), "bar": range(5, 10)})
>>> original_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> pd.to_pickle(original_df, "./dummy.pkl")
>>> unpickled_df = pd.read_pickle("./dummy.pkl")
>>> unpickled_df
foo bar
0 0 5
1 1 6
2 2 7
3 3 8
4 4 9
>>> import os
>>> os.remove("./dummy.pkl")