gpt4 book ai didi

python - Pandas - 从转换后的数据帧中检索原始数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:53 24 4
gpt4 key购买 nike

我构建了一个数据框,通过以下步骤保存一段时间内股票指数的股票成分:

1)首先,我通过数据提供者下载原始数据并存储在字典中

2)转化为dataframe得到:

constituent_pd = pd.DataFrame.from_dict(constituent, orient='index')

index col1 col2 col3 etc...
1/1/92 stockA stockB NA etc...
2/1/92 stockB stockC stockD etc...

3)转换为 bool 数据框:

constituent_bol = pd.get_dummies(constituent_pd.stack()).max(level=0).astype(bool)

index stockA stockB stockC etc...
1/1/92 True True False etc...
2/1/92 False True True etc...

从那时起,我一直在尝试找到一种快速更新我的表格的方法。为此,我需要将 Components_bin 重新转换回其原始字典形式,将其与新的 dictionart 合并(对于更新的日期)并重新启动整个过程。

step1 = constituent_bol.astype('int32')
step2 = step1[step1 ==1].stack().reset_index().drop(0,1).set_index('level_0')

1/1/92 stockA
1/1/92 stockB
etc...

而且我不知道如何 reshape 这个长数据帧,例如concentration_pd,以便稍后获得 dic。

感谢您的帮助!

最佳答案

问题在于函数 max(level=0) 丢失了原始列名称,因为它按第一级聚合。

如此接近您需要的内容可以使用 GroupBy.cumcount对于新列名称的计数器:

print (constituent_pd)
col1 col2 col3
index
1/1/92 stockA stockB NaN
2/1/92 stockB stockC stockD
<小时/>
print (pd.get_dummies(constituent_pd.stack()))
stockA stockB stockC stockD
index
1/1/92 col1 1 0 0 0
col2 0 1 0 0
2/1/92 col1 0 1 0 0
col2 0 0 1 0
col3 0 0 0 1

print (pd.get_dummies(constituent_pd.stack()).max(level=0))
stockA stockB stockC stockD
index
1/1/92 1 1 0 0
2/1/92 0 1 1 1
<小时/>
constituent_bol = pd.get_dummies(constituent_pd.stack()).max(level=0).astype(bool)
print (constituent_bol)
stockA stockB stockC stockD
index
1/1/92 True True False False
2/1/92 False True True True
<小时/>
step1 = constituent_bol.astype('int32')
step2 = step1[step1 == 1].stack().reset_index().drop(0,1)
step2 = step2.set_index(['index', step2.groupby('index').cumcount()])['level_1'].unstack()
print (step2)
0 1 2
index
1/1/92 stockA stockB NaN
2/1/92 stockB stockC stockD

关于python - Pandas - 从转换后的数据帧中检索原始数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55140871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com