gpt4 book ai didi

python - 将 Series 中的每个元素映射到 Series 并将结果组合到 DataFrame 中

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:35 28 4
gpt4 key购买 nike

例如,假设有一个系列

0     'pikachu'
1 'squirtle'

以及将神奇宝贝名称映射到由其颜色和重量组成的系列的映射。

例如,“皮卡丘”映射到该系列

color    'yellow'
weight 5

我想知道如何获得看起来像这样的 DataFrame

    pokemon    color       weight
0 pikachu 'yellow' 5
1 squirtle 'blue' 8

我目前能想到的解决方案由许多pd.concat组成,但我怀疑可能有更干净的方法。

最佳答案

如果将它们存储为字典:

In [11]: pika
Out[11]:
color yellow
weight 5
dtype: object

In [12]: squi
Out[12]:
color blue
weight 8
dtype: object

In [13]: pokes = {'pikachu': pika, 'squirtle': squi}

然后您可以使用 get 方法(获取名称并返回系列):

In [14]: pokemon
Out[14]:
0 pikachu
1 squirtle
dtype: object

In [15]: pokemon.apply(pokes.get)
Out[15]:
color weight
0 yellow 5
1 blue 8

注意:使用 _['name'] = pokemon 添加名称列。

或者您可以使用 from_dict 方法:

In [21]: pd.DataFrame.from_dict(pokes, orient='index')
Out[21]:
color weight
pikachu yellow 5
squirtle blue 8

关于python - 将 Series 中的每个元素映射到 Series 并将结果组合到 DataFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21977483/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com