Pandas IO操作

Pandas IO操作实例

读取文本文件的两个主要功能是read_csv()和read_table()。他们都使用相同的解析代码将表格数据智能地转换为DataFrame对象:

pandas.read_csv(filepath_or_buffer,sep=',',delimiter=None,header='infer',names=None,index_col=None,usecols=None
pandas.read_csv(filepath_or_buffer,sep='\t',delimiter=None,header='infer',names=None,index_col=None,usecols=None

将此数据另存为temp.csv并对其进行操作。

S.No,Name,Age,City,Salary1,Tom,28,Toronto,200002,Lee,32,HongKong,30003,Steven,43,BayArea,83004,Ram,38,Hyderabad,3900

read.csv

read.csv从csv文件读取数据并创建一个DataFrame对象。

importpandasaspddf=pd.read_csv("temp.csv")printdf

运行结果如下:

S.NoNameAgeCitySalary01Tom28Toronto2000012Lee32HongKong300023Steven43BayArea830034Ram38Hyderabad3900

自定义索引

这将在csv文件中指定一列,以使用index_col自定义索引。

importpandasaspddf=pd.read_csv("temp.csv",index_col=['S.No'])printdf

运行结果如下:

S.NoNameAgeCitySalary1Tom28Toronto200002Lee32HongKong30003Steven43BayArea83004Ram38Hyderabad3900

转换器

列的dtype可以作为dict传递。

importpandasaspddf=pd.read_csv("temp.csv",dtype={'Salary':np.float64})printdf.dtypes

运行结果如下:

S.Noint64NameobjectAgeint64CityobjectSalaryfloat64dtype:object

默认情况下,Salary列的dtype为int,但结果将其显示为float,因为我们已明确转换了类型。因此,数据看起来像float。

Thus, the data looks like float −

S.NoNameAgeCitySalary01Tom28Toronto20000.012Lee32HongKong3000.023Steven43BayArea8300.034Ram38Hyderabad3900.0

标题名称

使用names参数指定标题的名称。

importpandasaspddf=pd.read_csv("temp.csv",names=['a','b','c','d','e'])printdf

运行结果如下:

abcde0S.NoNameAgeCitySalary11Tom28Toronto2000022Lee32HongKong300033Steven43BayArea830044Ram38Hyderabad3900

请注意,标头名称后附加了自定义名称,但是文件中的标头尚未消除。现在,我们使用header参数将其删除。

如果标题不在第一行中,则将行号传递给标题。这将跳过前面的行。

importpandasaspddf=pd.read_csv("temp.csv",names=['a','b','c','d','e'],header=0)printdf

运行结果如下:

abcde0S.NoNameAgeCitySalary11Tom28Toronto2000022Lee32HongKong300033Steven43BayArea830044Ram38Hyderabad3900

skiprows

skiprows跳过指定的行数。

importpandasaspddf=pd.read_csv("temp.csv",skiprows=2)printdf

运行结果如下:

2Lee32HongKong300003Steven43BayArea830014Ram38Hyderabad3900
编辑于2024-05-20 14:34