答案 0 :(得分:2)
问题是您需要将函数Series.value_counts
应用于DataFrame
的aomecolumns,因此请使用apply
。
与:
相同df.apply(lambda s: s.value_counts())
#same as
df.apply(pd.value_counts)
答案 1 :(得分:0)
这是一种未记录的方法:
Signature: pd.value_counts(values, sort=True, ascending=False, normalize=False, bins=None, dropna=True)
Docstring:
Compute a histogram of the counts of non-null values.
Parameters
----------
values : ndarray (1-d)
sort : boolean, default True
Sort by values
ascending : boolean, default False
Sort in ascending order
normalize: boolean, default False
If True then compute a relative histogram
bins : integer, optional
Rather than count values, group them into half-open bins,
convenience for pd.cut, only works with numeric data
dropna : boolean, default True
Don't include counts of NaN
Returns
-------
value_counts : Series
如果您将列作为arg传递,则输出与pd.Series.value_counts
:
In [8]:
Offline_BackupSchemaIncrementType
df = pd.DataFrame({'Offline_BackupSchemaIncrementType': [0,1,1,2,np.NaN], 'val':np.arange(5)})
df
Out[8]:
Offline_BackupSchemaIncrementType val
0 0.0 0
1 1.0 1
2 1.0 2
3 2.0 3
4 NaN 4
In [9]:
pd.value_counts(df['Offline_BackupSchemaIncrementType'])
Out[9]:
1.0 2
2.0 1
0.0 1
Name: Offline_BackupSchemaIncrementType, dtype: int64
In [10]:
df['Offline_BackupSchemaIncrementType'].value_counts()
Out[10]:
1.0 2
2.0 1
0.0 1
Name: Offline_BackupSchemaIncrementType, dtype: int64
然而,当你apply
方法时,你正在为每个元素执行此操作,因此返回的Series正在尝试将其与原始df对齐,实际上你得到了一个二维数组:
In [7]:
df['Offline_BackupSchemaIncrementType'].apply(pd.value_counts)
Out[7]:
0.0 1.0 2.0
0 1.0 NaN NaN
1 NaN 1.0 NaN
2 NaN 1.0 NaN
3 NaN NaN 1.0
4 NaN NaN NaN
这里的值是列,索引与原始df
相同