![](/img/trans.png)
[英]Access multi index column names in groupby objects in pandas in for loop
[英]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.