簡體   English   中英

將字典轉換為熊貓中的數據框列

[英]converting dictionary to dataframe column in pandas

我有這樣的嵌套字典

  d = {1 : {'we': 26, 'is': 112},
       2 : {'tp': 26, 'fp': 91},
       3 : {'pp': 23, 'kj': 74}}

我想將其更改為數據框列,以便外部dict鍵變為行,並且其元素充當列的元素。

所需輸出:

  rows           col1      
  1      'we': 26, 'is': 112
  2      'tp': 26, 'fp': 91
  3      'pp': 23, 'kj': 74

如果這就是字典中的內容,則不一定要保留內部dict的鍵順序。

import pandas as pd
d = {1 : {'we': 26, 'is': 112},
     2 : {'tp': 26, 'fp': 91},
     3 : {'pp': 23, 'kj': 74}}
# Replace the inner dicts with their string representations
for i in d:
    d[i] = str(d[i])
# Convert to dataframe
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
# Clean up column names
df.rename(columns={'index': 'row', 0: 'col1'}, inplace=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM