从多个字典值列表创建数据帧

2024-06-16 08:24:26 发布

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

我有一个代码如下

safety_df ={}
for key3,safety in analy_df.items():
    safety = pd.DataFrame({"Year":safety['index'],
                      '{}'.format(key3)+"_CR":safety['CURRENT'],
                      '{}'.format(key3)+"_ICR":safety['ICR'],
                      '{}'.format(key3)+"_D/E":safety['D/E'],
                      '{}'.format(key3)+"_D/A":safety['D/A']})
    safety_df[key3] = safety 

在这段代码中,我从另一个字典中提取值。它将通过不同的公司循环,这就是我为什么在密钥中使用格式命名的原因。每个公司的输出包含以上5列(年度、CR、ICR、D/E、D/A)

正在打印输出的输出包含大量NA值,其中 在这里,我想要所有公司的通用栏,即年份,并打印以下栏,即C1_CR、C2_CR、C3_CR、C1_ICR、C2_ICR、C3_ICR、…C3_D/A

我尝试使用以下代码提取

pd.concat(safety_df.values())

此..的示例输出

enter image description here

在这里,它为每个列表提取值,但由于for循环,NA值被打印出来

我也尝试过groupby,但没有成功

如何将年份设置为公共列,并并排打印其他值

谢谢


Tags: 代码formatdffor公司crpd年份
1条回答
网友
1楼 · 发布于 2024-06-16 08:24:26

使用axis=1沿列连接:

import numpy as np
import pandas as pd

years = np.arange(2010, 2021)
n = len(years)
c1 = np.random.rand(n)
c2 = np.random.rand(n)
c3 = np.random.rand(n)

frames = {
    'a': pd.DataFrame({'year': years, 'c1': c1}),
    'b': pd.DataFrame({'year': years, 'c2': c2}),
    'c': pd.DataFrame({'year': years[1:], 'c3': c3[1:]}),
}
for key in frames:
    frames[key].set_index('year', inplace=True)

df = pd.concat(frames.values(), axis=1)
print(df)

导致

            c1        c2        c3
year
2010  0.956494  0.667499       NaN
2011  0.945344  0.578535  0.780039
2012  0.262117  0.080678  0.084415
2013  0.458592  0.390832  0.310181
2014  0.094028  0.843971  0.886331
2015  0.774905  0.192438  0.883722
2016  0.254918  0.095353  0.774190
2017  0.724667  0.397913  0.650906
2018  0.277498  0.531180  0.091791
2019  0.238076  0.917023  0.387511
2020  0.677015  0.159720  0.063264

请注意,我已显式地将索引设置为“year”列,在我的示例中,我已从“c”列中删除了第一年。这是为了显示在连接时不同数据帧的索引是如何匹配的。如果将索引保留为其标准值,您将得到不同步的年份,并在“c”列底部获得一个NaN值

相关问题 更多 >