【问题标题】:Make several columns using for loop?使用 for 循环制作几列?
【发布时间】:2020-01-02 21:02:48
【问题描述】:

下面的代码(计算 N 天的移动平均线)效果很好。但我想用 50 替换其他数字(例如 5、10、20 等)。不确定是否可以将以下代码转换为 for 循环中的内容。有人可以帮帮我吗?

df['ma50pfret']= df['ret']

df.loc[df.adjp >= df.ma50, 'adjp > ma50']= 1
df.loc[df.adjp < df.ma50, 'adjp > ma50']= 0
df.iloc[0, -1]= 1

df['adjp > ma50']= df['adjp > ma50'].astype(int)
df.loc[df['adjp > ma50'].shift(1)== 0, 'ma50pfret']= 1.000079 # 1.02**(1/250)

df['cum_ma50pfret']=df['ma50pfret'].cumprod()
df.head(10)

【问题讨论】:

  • 欢迎堆栈溢出!不幸的是,这个问题不够详细,无法为您提供任何有意义的帮助。请编辑您的问题以包含该问题的最小可重现示例,包括您迄今为止尝试过的示例输入和首选输出。

标签: python python-3.x pandas dataframe for-loop


【解决方案1】:

您的意思是用 5、10、20 等替换 50 吗?如果是这样,可以通过始终使用括号来访问列,并使用 f-strings(或其他一些字符串格式化方法)将 50 替换为其他数字来完成,如下所示:

for num in [5, 10, 20, 50]:
    df[f'ma{num}pfret']= df['ret']

    df.loc[df.adjp >= df[f'ma{num}'], f'adjp > ma{num}']= 1
    df.loc[df.adjp < df[f'ma{num}], f'adjp > ma{num}']= 0
    df.iloc[0, -1]= 1

    df[f'adjp > ma{num}']= df[f'adjp > ma{num}'].astype(int)
    df.loc[df[f'adjp > ma{num}'].shift(1)== 0, f'ma{num}pfret']= 1.000079 # 1.02**(1/250)

    df[f'cum_ma{num}pfret']=df[f'ma{num}pfret'].cumprod()

df.head(10)

【讨论】:

    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    相关资源
    最近更新 更多