在删除索引的同时使用Pandas向数据帧添加标头

2024-05-15 02:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,它被重新采样为一个较小的数据帧,它保留了一个日期时间索引。我转换了dataframe,现在希望删除dateindex并用字符串(标签)替换它,然后将其导出到.csv,以javascript可以读取的格式使用(在python中执行所有数据操作)。在

我确实尝试过不带标题(删除日期)将其写入.csv,然后再次读取以添加标签,但这似乎不太有效。在

链接到csv: https://www.dropbox.com/s/qy72yht2m7lk2pg/17_predicted.csv

Python/pandas代码:

import pandas as pd
import numpy as np
from dateutil.parser import parse
from datetime import datetime
from pandas import *

# Load csv into pandas DataFrame
df = pd.read_csv("17_predicted_dummydata.csv", parse_dates=True, dayfirst=False, keep_date_col=True, index_col=0)

#Creating a date range
df.index = pd.to_datetime(pd.date_range(start='1/1/2000 00:30:00', end='1/1/2000 05:00:00', freq='30T'))

#Rename index
df.index.name = 'date'

df_year = df.resample('D', how='sum')
df_year = np.round(df_year, 0)

df_year.index.name = 'label'
df_year.column = ['value']

df_year = df_year.T

print df_year.head()
print df_year.index.name

df_year.to_csv("17_dummy.csv") #drop index through header=False

CSV输入:

^{pr2}$

建议的csv输出:

    label,value
InteriorEquipment:Electricity:Zone:4419 [J](TimeStep),6.0
InteriorEquipment:Electricity:Zone:3967 [J](TimeStep),4.0
InteriorEquipment:Electricity:Zone:3993 [J](TimeStep),0.0

我试图遵循这个(Insert a row to pandas dataframe)解决方法,但没能成功。在

感谢任何帮助!在


Tags: csvto数据namefromimportpandasdf
1条回答
网友
1楼 · 发布于 2024-05-15 02:16:37

您可以直接分配给dataframe的索引名和列,使其按您的需要输出。在

In [288]: df_year.index.name = 'label'

In [289]: df_year.columns = ['value']

In [290]: print df_year.to_csv()
label,value
Equipment:Electricity:LGF,79468.0
Equipment:Electricity:GF,66724.0
Equipment:Electricity:1st,30700.0
Equipment:Electricity:2nd,24126.0
Lights:Electricity:LGF,30596.0
Lights:Electricity:GF,30596.0
Lights:Electricity:1st,14078.0
Lights:Electricity:2nd,11063.0
General:Equipment:Electricity,201018.0
General:Lights:Electricity,86334.0
Electricity:Facility,314318.0
Electricity:Building,287352.0
Electricity:Plant,6329.0
Gas:Facility,279252.0
Electricity:HVAC,20637.0
General:Fans:Electricity,3554.0
Cooling:Electricity,17083.0
Pumps:Electricity,3708.0
WaterSystems:Electricity,2621.0

相关问题 更多 >

    热门问题