I have a dataframe which I transposed to this:
df=df.T.reset_index()
index | 2020-01-01 | 2020-02-01 |....| 2021-09-01
book | 0.2 | 0.3 |.....
fruit | 0.1 | 0.11 |.....
Now, I want to plot a line chart which shows for every product ('index'), month over month a line with those respective values. However, when I transposed the df, it did something weird to the index and columns where df.info() gives me:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 14 entries, 0 to 13
Columns: 101 entries, index to 18.0
dtypes: float64(100), object(1)
How can I shape the df in order to plot?
CodePudding user response:
- you describe below, it works
- update question with real data if this does not work
df = pd.DataFrame(index=pd.date_range("1-jan-2021", freq="MS", periods=9), data=np.random.uniform(1,5,(9,2)), columns=["book","fruit"])
dfp = df.T.reset_index()
px.line(dfp.set_index("index").T).show()
dfp.info()
CodePudding user response:
import pandas as pd
from datetime import datetime
import numpy as np
import plotly.graph_objects as go
df = pd.DataFrame(data={'date': list(pd.date_range(datetime(2021, 1, 1), datetime(2021, 1, 10))),
'fruit': list(np.arange(1, 11, 1)),
'book': list(np.arange(21, 31))})
df=df.T.reset_index()
df.columns = df.loc[0]
df = df.loc[1:]
fig = go.Figure()
for index, row in df.iterrows():
fig.add_trace(go.Scatter(x=df.columns[1:], y=row[1:], mode='lines markers', name=row[0]))
fig.update_layout(title = 'Line plot of items', xaxis_title='Time', yaxis_title='Sales')
fig.show()
Input Dataframe
:
0 date 2021-01-01 00:00:00 ... 2021-01-09 00:00:00 2021-01-10 00:00:00
1 fruit 1 ... 9 10
2 book 21 ... 29 30
Figure: