简体   繁体   中英

How to read the data in Pandas's dataframe row wise and plot the values as a timeseries if column represents months and index is years?

I have one data frame which has months as a column and first column represents year. I want to plot the time-Series of this data frame ie reading each row and plotting a timeseries. I am providing a small part of my data frame below. Kindly let me know any way to perform this task.

YEAR JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC

0 1870 -0.02 -0.02 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01

1 1871 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 -0.01 0.00 0.00 0.00

and So on....

I assume you store your data in a pandas DataFrame in a form as follows(each row represents one year):

df = pd.DataFrame(np.array([[1870,0.02,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01],
                             [1871,0.02,0.02,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01]]),
                   columns =  ["YEAR", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"])

Which outputs df in this way:

     YEAR   JAN   FEB   MAR   APR   MAY  ...   JUL   AUG   SEP   OCT   NOV   DEC
0  1870.0  0.02  0.02  0.01  0.01  0.01  ...  0.01  0.01  0.01  0.01  0.01  0.01
1  1871.0  0.02  0.02  0.01  0.01  0.01  ...  0.01  0.01  0.01  0.01  0.01  0.01
[2 rows x 13 columns]

This is just a two-year sample with duplicate row entries.

What you need is something like below:

import matplotlib.pyplot as plt
cols = np.array(df.columns)[1:]
rows_size= df.shape[0]
x = np.empty((1, 0), str)
y = np.empty((1, 0), float)
for i in range (rows_size):
        x = np.append(x, str(int(df.iloc[i, 0]))+ "-" + cols.reshape(1,12) , axis = 1)
        y = np.append(y, np.array(df.iloc[i, 1:]).reshape(1,12), axis = 1)
x = x.reshape(-1)
y = y.reshape(-1)
plt.plot(x, y)
plt.xticks(x,x, rotation ='vertical')
plt.subplots_adjust(bottom = 0.2)
plt.show()

the resulting plot would be then something like: (图片)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM