从中绘图测向枢轴将索引作为xaxis目标时返回AttributeError

2024-06-16 13:00:27 发布

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

绘制跨区域的时间和温度数据。导入csv并将其重新格式化到数据透视表中以构建独特的列:

in: dfpiv2 = df.pivot(index = 'target_logtime', columns = 'valuekey', values = 'value') 

out: 

valuekey    5575    5579    5583    5587    5591    5599    5603    5607    5611    5615
target_logtime                                      
2016-02-01 00:00:00     22.87   21.87   19.68   18.18   10.43   19.93   18.93   19.00   19.18   19.62
2016-02-01 00:30:00     22.43   21.50   19.56   17.87   10.43   19.68   18.87   18.93   19.00   19.37
2016-02-01 01:00:00     22.18   21.25   19.43   17.62   10.43   19.50   18.81   18.87   18.81   19.12
2016-02-01 01:30:00     21.87   21.00   19.31   17.37   10.43   19.31   18.81   18.81   18.68   18.93
2016-02-01 02:00:00     21.68   20.75   19.18   17.18   10.37   19.12   18.75   18.75   18.50   18.75

一切似乎正常,但是,我想要在x轴上使用的target\u logtime列似乎消失了:

in: dfpiv2.columns    
out: Int64Index([5575, 5579, 5583, 5587, 5591, 5599, 5603, 5607, 5611, 5615], dtype='int64', name='valuekey')

我认为这是。。。你知道吗

AttributeError: 'DataFrame' object has no attribute 'target_logtime'

以下是我使用的完整代码:

import pandas as pd
df = pd.read_csv('******.csv')
dfpiv2 = df.pivot(index = 'target_logtime', columns = 'valuekey', values = 'value') 
import plotly
plotly.tools.set_credentials_file(username='********', api_key='*******')
import plotly.plotly as py
import plotly.graph_objs as go

#import dataset


# define x and y
x = dfpiv2.target_logtime
y1 = dfpiv2[5575]

# create a trace
trace1 = go.Scatter(
    x = x,
    y = y1,
    mode = 'lines',
    name = '5575'
)

data = [trace1]

py.iplot(data, filename='basiclinetest')

谢谢你的帮助!你知道吗


Tags: columnscsv数据inimporttargetdfindex
1条回答
网友
1楼 · 发布于 2024-06-16 13:00:27

数据透视表(dfpiv2)正在被target_logtime索引,因此,尝试将其作为列访问时出错。有两种方法可以访问这些值。你知道吗

重新索引

第一种方法是重置索引并使用dfpiv3 = dfpiv2.reset_index()将其重新分配给列。你知道吗

然后,在检查列时:

In: dfpiv3.columns
Out: Index(['target_logtime', 5575, 5579, 5583, 5587, 5591, 5599, 5603, 5607, 5611, 5615], dtype='object', name='valuekey')

它允许在通过plotly绘制折线图时使用target_logtime作为x轴(因为target_logtime再次存在)

访问索引值

通过plotly绘图时,也可以通过将x设置为index而不是所需的列名来避免重置索引:

x = dfpiv2.index
y1 = dfpiv2[5575]

谢谢p.Tillmann和xg.plt.py公司感谢他们的评论。你知道吗

相关问题 更多 >