【问题标题】:access the element in the for loop [duplicate]访问for循环中的元素[重复]
【发布时间】:2021-07-13 18:17:57
【问题描述】:

我根据年份和月份来分离我的数据框,但我想让它更加自动化。现在我必须对它们进行硬编码:

def year_month_open(c):
   c.Opened_Date.astype('string')
   x = c.Opened_Date.strftime('%Y-%m')

return x

df['year_month'] = df.apply(year_month_open,axis=1)`

Feb20 = df[df['year_month']=='2020-02']
Mar20 = df[df['year_month']=='2020-03']
Apr20 = df[df['year_month']=='2020-04']
May20 = df[df['year_month']=='2020-05']
Jun20 = df[df['year_month']=='2020-06']
Jul20 = df[df['year_month']=='2020-07']
Aug20 = df[df['year_month']=='2020-08']
Sep20 = df[df['year_month']=='2020-09']
Oct20 = df[df['year_month']=='2020-10']
Nov20 = df[df['year_month']=='2020-11']
Dec20 = df[df['year_month']=='2020-12']
Jan21 = df[df['year_month']=='2021-01']
Feb21 = df[df['year_month']=='2021-02']
Mar21 = df[df['year_month']=='2021-03']

您能否建议一种方法来避免对它们进行编码,这样当我为下个月附加另一个数据集时,我不必输入

Apr21 = Mar21 = df[df['year_month']=='2021-04']

【问题讨论】:

  • 您正在为所有可能的年月组合手动创建二进制假人Feb20.,...,Mar21pd_get_dummies() 这样做:将分类变量转换为虚拟/指标变量。您可以自动执行此操作,正如答案所说,您可能不需要这样做 - 您为什么要这样做,用于分类或回归?
  • 参见例如pandas how to 'get_dummies' on time series data。您只想在df['year_month'] 上致电pd.get_dummies

标签: python pandas dataframe


【解决方案1】:

首先,我建议您考虑您是否真的需要这样做,或者其他解决方案(例如函数)是否更合适。例如,如果您使用带有月份-年份字符串作为索引的多索引,则可以只执行 df['Apr21'] 而不是创建单独的数据框。如果你想创建单独的变量,有以下内容,但请记住,你应该小心eval 函数(如果命令进入year_month 列,那可能非常危险)。

import calendar

def convert_date(date)
    year = date[:4]
    month_num = date[4:]
    month = calendar.month_name[int(month_num)][:3]
    return month+year

for group in df.groupby(year_month):
    month_name = convert_date(group[0])
    month_df = group[1]
    eval("{} = month_df".format(month_name))

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2016-02-12
    • 2020-04-14
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 2020-11-18
    • 2020-08-02
    • 2020-08-24
    相关资源
    最近更新 更多