【问题标题】:converting dict into a dataframe? [duplicate]将dict转换为数据框? [复制]
【发布时间】:2020-08-07 15:39:46
【问题描述】:
{'student1': 45,
 'student2': 78,
 'student3': 12,
 'student4': 14,
 'student5': 48,
 'student6': 43,
 'student7': 47,
 'student8': 98,
 'student9': 35,
 'student10': 80}

如何将此字典转换为数据框

【问题讨论】:

  • pandas.DataFrame.from_dict(data, orient='columns', dtype=None, columns=None) → 'DataFrame'

标签: python


【解决方案1】:
import pandas as pd

student = {
    "student1": 45,
    "student2": 78,
    "student3": 12,
    "student4": 14,
    "student5": 48,
    "student6": 43,
    "student7": 47,
    "student8": 98,
    "student9": 35,
    "student10": 80,
}

df = pd.DataFrame(student.items(), columns=["name", "score"])
print(df)
        name  score
0   student1     45
1   student2     78
2   student3     12
3   student4     14
4   student5     48
5   student6     43
6   student7     47
7   student8     98
8   student9     35
9  student10     80

【讨论】:

  • 如果您想使用名称作为索引,请执行df.set_index("name")
【解决方案2】:
import pandas as pd 

# intialise data of lists. where each key will be your column 
data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]} 

# Create DataFrame 
df = pd.DataFrame(data) 

# or list of dicts
data = [{'a': 1, 'b': 2, 'c':3}, {'a':10, 'b': 20, 'c': 30}] 

如果您遇到标量错误

这样做

import pandas as pd

data = {'student1': 45, 'student2': 78, 'student3': 12, 'student4': 14, 'student5': 48, 'student6': 43, 'student7': 47, 'student8': 98, 'student9': 35, 'student10': 80}
for i in data.keys():
    data[i] = [data[i]]
df = pd.DataFrame(data)
df.head()

【讨论】:

    【解决方案3】:

    这应该可以解决问题

    df = DataFrame(list(my_dict.items()),columns = ['column1','column2'])
    

    【讨论】:

      【解决方案4】:
      pd.DataFrame(dict_.items())
      
      pd.DataFrame(dict_.items(), columns=['Student', 'Point'])
      
      pd.Series(dict_, name='StudentValue')
      

      一切都会好起来的。

      【讨论】:

        猜你喜欢
        • 2019-09-27
        • 2013-09-21
        • 2021-08-07
        • 2022-08-11
        • 2021-10-15
        • 2018-08-02
        • 2017-05-16
        • 2016-02-18
        相关资源
        最近更新 更多