简体   繁体   中英

How to iterate over the columns of a dataframe and plot columns using a for loop in Python

I want to plot the columns of a dataframe by iterating over the index of the columns in a for loop. I want to plot the second column against the third and save the figure with the name of the thrid column's name in the dataframe (my first column is just the index of the rows). I want to do this using the index of the columns and not the column names.

Here is what I tried:

import pandas as pd
from matplotlib import pyplot as plt

alldata = pd.read_csv('alldata.csv')

x=alldata.ix[:, 2::2]
y=alldata.iy[:, 1::2]

for i, column in alldata.iteritems():
    xi = x[i]
    for k, column in force.iteritems():
        yi = y[k]
        plt.plot(xi, yi)
        plt.show()
alldata=pd.read_csv("alldata.csv")

x=alldata.iloc[:, 1]
y=alldata.iloc[:, 2]

# or plt.scatter(x, y)
for i in range(len(x)):
    plt.plot(x[i], y[i], marker=".")

fig=plt.gcf()
p="".join([alldata.columns[2], ".png"])
fig.savefig(p)

alldata.csv looks like

   index  secondcol  thirdcol
0      1          1         6
1      2          8         4
2      3          3         9
3      4          5         4
4      5          4         6
5      6          6         4
6      7          7         8
7      8          2         3

thirdcol.png looks 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