【发布时间】: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