Python Pandas:转换“.value_counts"输出到数据帧 [英] Python Pandas: Convert ".value_counts" output to dataframe
本文介绍了Python Pandas:转换“.value_counts"输出到数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取数据帧的唯一值的计数.count_values 实现了这一点,但是我想在其他地方使用它的输出.如何将 .count_values 输出转换为 Pandas 数据帧.这是一个示例代码:
Hi I want to get the counts of unique values of the dataframe. count_values implements this however I want to use its output somewhere else. How can I convert .count_values output to a pandas dataframe. here is an example code:
import pandas as pd
df = pd.DataFrame({'a':[1, 1, 2, 2, 2]})
value_counts = df['a'].value_counts(dropna=True, sort=True)
print(value_counts)
print(type(value_counts))
输出为:
2 3
1 2
Name: a, dtype: int64
<class 'pandas.core.series.Series'>
我需要的是这样的数据框:
What I need is a dataframe like this:
unique_values counts
2 3
1 2
谢谢.
推荐答案
使用 rename_axis
用于索引和 reset_index
:
df = df.value_counts().rename_axis('unique_values').reset_index(name='counts')
print (df)
unique_values counts
0 2 3
1 1 2
或者如果需要一列 DataFrame 使用 Series.to_frame
:
Or if need one column DataFrame use Series.to_frame
:
df = df.value_counts().rename_axis('unique_values').to_frame('counts')
print (df)
counts
unique_values
2 3
1 2
这篇关于Python Pandas:转换“.value_counts"输出到数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文