熊猫数据框中每一列的唯一值和计数

时间:2018-10-31 12:58:44

标签: python pandas testing

我已经建立了此测试来探索数据集中的问题。现在,我想对其进行扩展,以便对最频繁和最不频繁的值进行计数(最多10个值,但是如果这是可调整的,那会很好)

lvl1 = ['A','A','A','A','A','B','B','B','B',np.nan ]
lvl2 = ['foo','foo','bar','bar','bar','foo','foo','foo','bar','bar']
lvl3=  [1,1,1,2,2,3,3,4,5,6]
df = pd.DataFrame({ 'L1' : lvl1, 'L2' : lvl2, 'L3':lvl3})


df.apply(lambda x: [ 100*(1-x.count()/len(x.index)),x.dtype,x.unique()],result_type='expand').T.rename(index=str, columns={0: "Nullity %", 1: "Type",2:"Unique Values"})

这给出了

 Nullity %   Type    Unique Values
L1  10        object  [A, B, nan]
L2  0         object  [foo, bar]
L3  0         int     [1,2,3,4,5,6]

如何将其扩展为:

   Nullity %   Type    UniuqueValue1 UniuqueValue2 UniuqueValue3 ... UniuqueValue-3  UniuqueValue-2  UniuqueValue-1
L1  10         object  A:5               B:4          nan:1
L2  0          object  foo:5             bar:5
L3  0           int    1:3               2:2           3:2      ...   4:1             5:1               6:1  

编辑: 到目前为止,我设法做到了这一点。

c1=df['L1'].value_counts(dropna=False).reset_index()

c1['L1']=c1['index'].astype(str)+'('+c1['L1'].astype(str)+')'

c1.drop('index', axis=1).T

给出

    0       1       2
L1  A(5)    B(4)    nan(1)

0 个答案:

没有答案