如何绘制Pandas数据框的特定列?

5

很遗憾它不起作用:我有一个名为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)。

感谢您的帮助!!!

Helmut


2
使用.iloc[]吗? - Celius Stingher
1个回答

1
你可以使用.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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接