【问题标题】:Faster way to make dataframe from dictionary in Python在 Python 中从字典制作数据框的更快方法
【发布时间】:2020-07-12 21:47:56
【问题描述】:

我正在尝试像这样从字典中制作 pd.DataFrame:

x = {6: 8416, 2: 8361, 5: 8343, 4: 8326, 1: 8292, 3: 8262}

我希望这两个数字作为单独列中的一行,并添加列名“Y”和“Z”。 我以某种方式手动完成了它,但我正在寻找更快的方法来处理无法再手动完成的数据集

【问题讨论】:

  • pd.DataFrame([(k,v) for k,v in x.items()], columns=["Y","Z"])

标签: python-3.x pandas dataframe dictionary


【解决方案1】:

你可以这样做

x = {6: 8416, 2: 8361, 5: 8343, 4: 8326, 1: 8292, 3: 8262}
pd.DataFrame([(k,v) for k,v in x.items()], columns=["Y","Z"])

输出:

   Y     Z
0  6  8416
1  2  8361
2  5  8343
3  4  8326
4  1  8292
5  3  8262

【讨论】:

    【解决方案2】:

    这里是单向:

     pd.DataFrame.from_dict(x, 'index', columns=['y']).rename_axis('x').reset_index()
    

    输出:

       x     y
    0  6  8416
    1  2  8361
    2  5  8343
    3  4  8326
    4  1  8292
    5  3  8262
    

    【讨论】:

    • 我已将其发布为答案
    • @bigbounty +1 很棒的解决方案。
    猜你喜欢
    • 2017-01-13
    • 2016-06-09
    • 2011-05-08
    • 2011-08-17
    • 2020-06-10
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多