首页  

pandas read_csv 和 to_csv 索引问题     所属分类 python 浏览量 42
to_csv ,索引会保存到csv文件中,read_csv 时,把索引当成内容读了出来,然后再次默认加了一层索引


不存索引
df.to_csv(path,index=False)
会丢失索引数据 (某些情况不适用)

声明文件第一列为索引,第一行为列名(默认,可不指定)
df = pd.read_csv(path,index_col=0,header=0)
如果索引为 时间格式  注意转换 


code='510300.XSHG' df = get_price(code, start_date='2024-05-01', end_date='2024-05-07', frequency='daily', fields=['open','close']) df.head() open close 2024-05-06 3.640 3.648 2024-05-07 3.645 3.650 注意索引列没有名字 df.info() class 'pandas.core.frame.DataFrame' DatetimeIndex: 2 entries, 2024-05-06 to 2024-05-07 Data columns (total 2 columns): open 2 non-null float64 close 2 non-null float64 dtypes: float64(2) memory usage: 48.0 bytes df.to_csv('tmp.txt') ,open,close 2024-05-06,3.64,3.648 2024-05-07,3.645,3.65 import pandas as pd df = pd.read_csv('tmp.txt') df.head() Unnamed: 0 open close 0 2024-05-06 3.640 3.648 1 2024-05-07 3.645 3.650 class 'pandas.core.frame.DataFrame' RangeIndex: 2 entries, 0 to 1 Data columns (total 3 columns): Unnamed: 0 2 non-null object open 2 non-null float64 close 2 non-null float64 dtypes: float64(2), object(1) memory usage: 128.0+ bytes 列数 和 索引列不对 !!! 读取时指定索引列,并转换成 时间 import pandas as pd df = pd.read_csv('tmp.txt',index_col=0) # 转成 时间 !!! df.index = pd.to_datetime(df.index) df.head() open close 2024-05-06 3.640 3.648 2024-05-07 3.645 3.650 df.info() class 'pandas.core.frame.DataFrame' DatetimeIndex: 2 entries, 2024-05-06 to 2024-05-07 Data columns (total 2 columns): open 2 non-null float64 close 2 non-null float64 dtypes: float64(2) memory usage: 48.0 bytes

上一篇     下一篇
沪深300指数 bias250 z20 z250 分析

聚宽 沪深300指数 数据读取分析

油车 电车 使用成本

大模型简介

国内大模型

python pandas 使用技巧