【问题标题】:build a DataFrame with columns from tuple of arrays用数组元组中的列构建一个 DataFrame
【发布时间】:2016-12-29 10:53:21
【问题描述】:

我正在努力完成从np.unique(arr, return_counts=True) 生成的元组中按值构建计数的 DataFrame 的基本任务,例如:

import numpy as np
import pandas as pd

np.random.seed(123)  
birds=np.random.choice(['African Swallow','Dead Parrot','Exploding Penguin'], size=int(5e4))
someTuple=np.unique(birds, return_counts = True)
someTuple
#(array(['African Swallow', 'Dead Parrot', 'Exploding Penguin'], 
#       dtype='<U17'), array([16510, 16570, 16920], dtype=int64))

第一次尝试

pd.DataFrame(list(someTuple))
# Returns this:
#                  0            1                  2
# 0  African Swallow  Dead Parrot  Exploding Penguin
# 1            16510        16570              16920

我也试过pd.DataFrame.from_records(someTuple),它返回同样的东西。

但我正在寻找的是这个:

#              birdType      birdCount
# 0     African Swallow          16510  
# 1         Dead Parrot          16570  
# 2   Exploding Penguin          16920

正确的语法是什么?

【问题讨论】:

  • 您的第二种方法将与附加的“.T”功能接近:pd.DataFrame.from_records(someTuple).T

标签: python pandas numpy dataframe


【解决方案1】:

这是一个基于 NumPy 的解决方案,带有 np.column_stack -

pd.DataFrame(np.column_stack(someTuple),columns=['birdType','birdCount'])

或者np.vstack -

pd.DataFrame(np.vstack(someTuple).T,columns=['birdType','birdCount'])

np.transposenp.column_stacknp.vstack 进行基准测试,将1D 数组放入列中以形成2D 数组-

In [54]: tup1 = (np.random.rand(1000),np.random.rand(1000))

In [55]: %timeit np.transpose(tup1)
100000 loops, best of 3: 15.9 µs per loop

In [56]: %timeit np.column_stack(tup1)
100000 loops, best of 3: 11 µs per loop

In [57]: %timeit np.vstack(tup1).T
100000 loops, best of 3: 14.1 µs per loop

【讨论】:

  • 这些都是非常快速的 numpy 解决方案,正是我想要的。一个同样快速的答案是 pd.DataFrame(np.transpose(someTuple), columns=['birdType', 'birdCount']) 另一个用户给出但随后被删除(不知道为什么)。
  • @C8H10N4O2 在这三个上添加了一些时间,看起来都一样快。
【解决方案2】:

使用您的元组,您可以执行以下操作:

In [4]: pd.DataFrame(list(zip(*someTuple)), columns = ['Bird', 'BirdCount'])
Out[4]: 
                Bird  BirdCount
0    African Swallow      16510
1        Dead Parrot      16570
2  Exploding Penguin      16920

【讨论】:

    【解决方案3】:

    创建字典

    pd.DataFrame(dict(birdType=someTuple[0], birdCount=someTuple[1]))
    

    【讨论】:

    • 不错。我需要更频繁地开始使用带有关键字参数的普通字典构造函数。真的很方便。
    • 期待峡湾!
    【解决方案4】:

    你可以使用计数器。

    from collections import Counter
    
    c = Counter(birds)
    
    >>> pd.Series(c)
    African Swallow      16510
    Dead Parrot          16570
    Exploding Penguin    16920
    dtype: int64
    

    您也可以在该系列中使用value_counts

    >>> pd.Series(birds).value_counts()
    Exploding Penguin    16920
    Dead Parrot          16570
    African Swallow      16510
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 2020-10-15
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2020-02-11
      • 2021-06-26
      • 2013-09-10
      • 1970-01-01
      相关资源
      最近更新 更多