如何将Python,Pandas Dataframe中具有多对日期和观测值的每行绘制为x轴上的日期和y轴上的观测值?
IndexColumn、Date1、Value1、Date2、Value2、Date3、Value3
xyz,1/1/2020,2,2/2/2020,3,3/3/2020,4
abc,1/2/2020,4,2/6/2020,7,3/9/2020,8
发布于 2020-07-18 23:55:01
我能想到两个选择。
选项1:重塑DataFrame
下面,我们只需要抓取Date1、Value1和Date2、Value2等,然后将它们堆叠在一起形成一个新的数据帧。
import matplotlib.pyplot as plt
rename_func = lambda x: 'Date' if 'Date' in x else 'Value'
new_df = pd.concat([df[['Date'+str(i),'Value'+str(i)]].rename(str,columns=rename_func) for i in [1,2,3]])
# first is a scatter plot, second is a line plot. Uncomment whichever you want!
#plt.scatter(new_df['Date'],new_df['Value'])
#plt.plot(new_df['Date'],new_df['Value'])选项2:按原样绘制
您可以只绘制散点图,而无需更改任何内容,而无需对数据进行整形。如果你这样做,你就不能很容易地画出像上面那样的线条图。
import matplotlib.pyplot as plt
plt.scatter(df['Date1'],df['Value1'],color='blue')
plt.scatter(df['Date2'],df['Value2'],color='blue')
plt.scatter(df['Date3'],df['Value3'],color='blue')https://stackoverflow.com/questions/62959611
复制相似问题