簡體   English   中英

Python Pandas 在 for 循環中訪問列名

[英]Python pandas access column names in for loop

我有一個適用於各個列名的代碼:

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

我想繪制餅干、冰淇淋、糖果和蜂蜜。 下面的代碼工作正常

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))

對於相同的代碼,我想使用除少數列之外的所有列,而不像餅干、蜂蜜等單獨指定列名

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))

它不工作。 如何擁有所有列而不是僅自定義列名稱。

編輯:(不是下面已回答的原始問題的一部分):

還有一件事,除了刪除幾列之外,我只想包括自定義列,比如在這種情況下的第 1、3 和 4 列(需要通用解決方案)(即餅干、糖果和蜂蜜)使用列位置,可以在這種情況下,有人補充回答嗎?

我會解決它定義arr沒有你不想要的列,然后使用for循環:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM