如何绘制数据帧的特定列?

2024-05-18 08:45:25 发布

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

不幸的是,它不起作用:我有一个名为df的数据帧

它由5列和100行组成

我想在x轴列0(时间)和y轴上绘制相应的值

我试过:

figure, ax1 = plt.subplots()
ax1.plot(df.columns[0],df.columns[1],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df.columns[0],df.columns[2],linewidth=0.5,zorder=1, label = "Force2")

但这是行不通的

我不能直接称呼列名-我只能使用列的编号(如1、2或3)

谢谢你的帮助

赫尔穆特


Tags: columns数据dfplot时间绘制pltlabel
1条回答
网友
1楼 · 发布于 2024-05-18 08:45:25

您可以使用.iloc[]和列位置,也可以通过.columns将其作为参数传递:

figure, ax1 = plt.subplots()
ax1.plot(df[df.columns[0]],df[df.columns[1]],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df[df.columns[0]],df[df.columns[2]],linewidth=0.5,zorder=1, label = "Force2")

或与.iloc[]一起:

figure, ax1 = plt.subplots()
ax1.plot(df.iloc[:,0],df.iloc[:,1],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df.iloc[:,0],df.iloc[:,2],linewidth=0.5,zorder=1, label = "Force2")

或者,定义列名称列表,然后传递其索引(与第一个方法相同):

cols = df.columns
figure, ax1 = plt.subplots()
ax1.plot(df[cols[0]],df[cols[1]],linewidth=0.5,zorder=1, label = "Force1")
ax1.plot(df[cols[0]],df[cols[2]],linewidth=0.5,zorder=1, label = "Force2")

相关问题 更多 >