【问题标题】:Convert mutliple columns of dataFrame to a dictionary and store in a new column [closed]将dataFrame的多列转换为字典并存储在新列中[关闭]
【发布时间】:2021-11-01 01:24:22
【问题描述】:

我是 Pandas 的新手,正在努力实现以下目标: 我有一个如下所示的数据框:

                   Country     Capital        Area  Population

0                  Russia        Moscow         6601670   146171015

1                  Canada       Ottawa         3855100    38048738

2                  China        Beijing         3705407  1400050000

如何将其转换为如下所示的数据框:

                    Country       Details 

0                    Russia       {Capital: Moscow, Area:6601670, Population: 146171015}

1                    Canada       {Capital: Ottawa, Area:3855100, Population: 38048738}

2                     China       {Capital: Ottawa, Area:3705407, Population: 1400050000}

我想从原始数据框中删除列,并将它们作为字典存储在同一数据框中的新列中

【问题讨论】:

  • 您尝试过什么了吗? Pandas 有一个叫to_dict 你知道的东西。

标签: python pandas dataframe dictionary


【解决方案1】:
In [32]: # set a default value for the new column "Details"

In [33]: df['Details'] = None

In [34]: # create an empty list called details

In [35]: details = []

In [36]: # then iterate over the rows

In [37]: for index, row in df.iterrows():
    ...:     details.append({'Capital': row.Capital, 'Area': row.Area, 'Population'
    ...: : row.Population})
    ...: 
    ...: 
    ...: 

In [38]: # now you have all the details

In [48]: df.drop(['Capital', 'Area', 'Population'], axis=1, inplace=True)

In [49]: df
Out[49]: 
  Country                                            Details
0  Russia  {'Capital': 'Moscow', 'Area': 6601670, 'Popula...
1  Canada  {'Capital': 'Ottawa', 'Area': 3855100, 'Popula...
2   China  {'Capital': 'Beijing', 'Area': 3705407, 'Popul...

In [50]: # VOILA!

In [51]: 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 2014-01-30
    • 2020-10-06
    • 2014-01-05
    • 2021-11-28
    • 1970-01-01
    相关资源
    最近更新 更多