从字典中创建数据框的最佳方法是什么,dict键是元组:(索引,列)?

发布于 2025-02-09 12:10:44 字数 497 浏览 0 评论 0原文

我有一个以下格式的字典:

 tuple_key_dict = {
     (0, 'Q2'): 0.41,
     (1, 'Q2'): 0.52,
     (2, 'Q2'): 0.61,
     (0, 'Q3'): 0.66,
     (1, 'Q3'): 0.53,
     (3, 'Q3'): 0.66,
     (0, 'Q4'): 0.47,
     (1, 'Q4'): 0.52,
     (2, 'Q4'): 0.67
          }

我也有列名的列表:

interesting_columns=['Q2', 'Q3', 'Q4']

...知道索引在范围(0,1000)。使用了所有COLMN名称和索引,但是缺少一些组合(例如,在上面的示例中:(2,'q2')

。键)是索引,第二个是列名(值是dicitionary值)。我尝试了多种我什至不想在这里提及的方式 - 所有的失败了痛苦:)

I have a dictionary in the following format:

 tuple_key_dict = {
     (0, 'Q2'): 0.41,
     (1, 'Q2'): 0.52,
     (2, 'Q2'): 0.61,
     (0, 'Q3'): 0.66,
     (1, 'Q3'): 0.53,
     (3, 'Q3'): 0.66,
     (0, 'Q4'): 0.47,
     (1, 'Q4'): 0.52,
     (2, 'Q4'): 0.67
          }

I also have a list of column names:

interesting_columns=['Q2', 'Q3', 'Q4']

... and know that index is in range (0,1000). All colmn names and indices are used, but a few combinations are missing (eg. in example above: (2, 'Q2').)

The job here is to have all these in a nice dataframe where the first element of the tuple (key) is the index and the second one is the column name (and values are the dicitionary values). I tried a number of ways I don't even wanna mention here - all failed miserably :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里人 2025-02-16 12:10:44

我认为当您写下Compination (2,'Q2')的情况下,您就遇到了一个错别字,我将没有值为NAN值的单元格保留。

代码

tuple_key_dict = {
     (0, 'Q2'): 0.41,
     (1, 'Q2'): 0.52,
     (2, 'Q2'): 0.61,
     (0, 'Q3'): 0.66,
     (1, 'Q3'): 0.53,
     (3, 'Q3'): 0.66,
     (0, 'Q4'): 0.47,
     (1, 'Q4'): 0.52,
     (2, 'Q4'): 0.67
          }
columns = ["Q2", "Q3", "Q4"]
# our indexes are a set that contains all the first item of the keys
indexes = {key[0] for key in tuple_key_dict}
df = pd.DataFrame(index=indexes, columns=columns)
for key, value in tuple_key_dict.items():
     df.at[key[0], key[1]] = value
print(df)

输出

     Q2    Q3    Q4
0  0.41  0.66  0.47
1  0.52  0.53  0.52
2  0.61   NaN  0.67
3   NaN  0.66   NaN

I assume that you made a typo when you wrote that the combination (2, 'Q2') is missing, I kept the cells that don't have values as NaN.

Code

tuple_key_dict = {
     (0, 'Q2'): 0.41,
     (1, 'Q2'): 0.52,
     (2, 'Q2'): 0.61,
     (0, 'Q3'): 0.66,
     (1, 'Q3'): 0.53,
     (3, 'Q3'): 0.66,
     (0, 'Q4'): 0.47,
     (1, 'Q4'): 0.52,
     (2, 'Q4'): 0.67
          }
columns = ["Q2", "Q3", "Q4"]
# our indexes are a set that contains all the first item of the keys
indexes = {key[0] for key in tuple_key_dict}
df = pd.DataFrame(index=indexes, columns=columns)
for key, value in tuple_key_dict.items():
     df.at[key[0], key[1]] = value
print(df)

Output

     Q2    Q3    Q4
0  0.41  0.66  0.47
1  0.52  0.53  0.52
2  0.61   NaN  0.67
3   NaN  0.66   NaN
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文