在数据帧上循环以保存手动重复的任务

2024-10-03 15:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经手动完成了以下任务,我确信有一种方法可以编写循环,但我不确定如何在Python中这样做。你知道吗

数据如下所示:

测向

                   a   b   c   market   ret
date        id                           
2015-01-01  1     10   4   2     10     0.02
2015-01-01  2     20   3   5     15     0.03
2015-01-01  3     30   2   3     20     0.05 
2015-01-01  4     40   1   10    25     0.01
2015-01-02  1     15   8   4     15    -0.03
2015-01-02  2     10   6   1     10     0.02
2015-01-02  3     25  10   2     22     0.06
2015-01-02  4     30   3   7     26     0.06
2015-01-03  1     25   2   2     16    -0.07
2015-01-03  2     10   6   1     18     0.01
2015-01-03  3     5    8   5     26     0.04
2015-01-03  4     30   1   6     21    -0.05

我做了以下工作:

dfa = df

dfa['market'] = dfa.groupby(level = ['id']).market.shift()

dfa['port'] = dfa.groupby(['date'])['a'].transform(lambda x: pd.qcut(x, 4, labels = False))

# value-weighted portoflio returns
dfa = dfa.set_index(['port'], append = True)
dfa['tmktcap'] = dfa.groupby(['date','port'])['mktcap'].transform(sum)
dfa['w_ret'] = (dfa.mktcap / dfa.tmktcap) * dfa.ret

#reshape long to wide
dfa = dfa.groupby(['date', 'port'])['w_ret'].sum().shift(-4)
dfa = dfa['2006-01-01':].rename('a')
dfa = dfa.unstack()
dfa[4.0] = dfa[3.0] - dfroe[0.0] 
dfa = dfa.stack().reset_index().set_index(['date'])
dfa['port'] = dfa['port'].map({0.0:'a0',1.0:'a1',2.0:'a2',3.0:'a3',4.0:'aL-S'})
dfa = dfa.reset_index().set_index(['date', 'port']).unstack()

然后我对b和c重复这个任务

所以我从设置dfb = df开始,把a改成b,然后对c执行这个过程。你知道吗

我不得不对从ah的变量(这里只使用了一些示例数据)这样做,所以任何关于编写循环的帮助都是惊人的!!!!!你知道吗


Tags: 数据iddfdateindexshiftporttransform
1条回答
网友
1楼 · 发布于 2024-10-03 15:32:49

循环选择列。 然后将结果保存在数组、列表或字典中。下面是一个列表示例。你知道吗

results = [] # this list will store your results
columns_to_process = ['a', 'b','c','d','f']

for col in columns_to_process:
    data = df.copy()
    data['market'] = data.groupby(level = ['id']).market.shift()
    data['port'] = data.groupby(['date'])[col].transform(lambda x: pd.qcut(x, 4, labels = False))

    # do whatever you want with data

    results.append(data) # this store the result in position 0 then 1 then 2 etc

#then use your result:

result[0] # for the dfa
result[1] # for dfb etc

或者,您可能希望将所有结果存储在一个数据帧中。为此,只需选择所需的列并将其保存在数据帧中。你知道吗

df['result_a'] = data.columns_i_want_to_save

你问:

#Do I just change a to col where I change name of the column?
dfa['port'].map({0.0:'a0',1.0:'a1',2.0:'a2',3.0:'a3',4.0:'aL-S'})

你可以做一些“字符串加法”。比如:

    dfa['port'].map({0.0:col+'0',
                     1.0:col+'1',
                     2.0:col+'2',
                     3.0:col+'3',
                     4.0:col+'L-S'})

相关问题 更多 >