noob
noob

Reputation: 3811

Python pandas access column names in for loop

I have a code which works well with individual column names:

df

Date         Biscuits  Ice cream   Candies   Honey  year  month
2017-12-1    12         23          44        3     2017   Dec
2019-11-1    11         20          10        4     2019   Nov
2018-10-1    4          11           NAN      2     2018   Oct

I wish to plot Biscuits, Ice creams, candies and say honey. The below code works fine

import matplotlib.pyplot as plt
from matplotlib import dates as mdates
# Plot the data
fig, ax = plt.subplots(figsize=(10, 2))
for col in ['Biscuits','Ice Cream','Candies','Honey']:
    ax.plot(df['Date'], df[col], label=col)
years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

For the same code, I wanted to use all the columns except few columns without specifying the column names separately like biscuits, honey etc

import matplotlib.pyplot as plt
from matplotlib import dates as mdates
# Plot the data
fig, ax = plt.subplots(figsize=(10, 2))
arr=df.columns.value_counts().drop(['year'],['Date'],['month']).index #this is where we need all columns except few columns
for col in arr:
    ax.plot(df['Date'], df[col], label=col)
years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

It is not working. How to have all the columns instead of custom column names only.

EDIT:(Not part of original question which has been answered below):

Just one more thing, lets say apart from dropping few columns, I want to include only custom columns, say column 1, 3 and 4 in this case(need a generic solution)(i.e. Biscuits , Candies and Honey) using column position, can anyone add to answer in that case?

Upvotes: 0

Views: 94

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18367

I would solve it defining arr without the columns you don't want and later use the for loop:

arr=df.drop(columns=['year','Date','month']) #this is where we need all columns except few columns
for col in arr:
    ax.plot(df['Date'], df[col], label=col)

Upvotes: 5

Related Questions