Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从Pandas value_counts()结果中提取值_Python_Pandas - Fatal编程技术网

Python 如何从Pandas value_counts()结果中提取值

Python 如何从Pandas value_counts()结果中提取值,python,pandas,Python,Pandas,执行df.['ColumnName'].value_counts()后,要对数据帧的列中的唯一字符串进行计数,我将得到以下格式的结果: a 4 b 2 c 5 Name: ColumnName, dtype: int64 如何从这些结果中提取值?例如,我如何获得“b”或2?它是系列,所以使用方法, , , : 测试: s = pd.Series([4,2,5], index=['a','b','c']) #get value by label s.loc['b'] #2 s

执行
df.['ColumnName'].value_counts()
后,要对数据帧的列中的唯一字符串进行计数,我将得到以下格式的结果:

a    4
b    2
c    5
Name: ColumnName, dtype: int64

如何从这些结果中提取值?例如,我如何获得“b”或2?

它是
系列
,所以使用方法, , , :

测试

s = pd.Series([4,2,5], index=['a','b','c'])

#get value by label
s.loc['b'] #2
s.at['b'] #2

#get value by position
s.iloc[1]  #2
s.iat[1]  #2
s[1] #2

#get index by value
s.index[s.eq(2)].item() #b

#get index value by position
s.index[1] #b

例如,您可以使用索引从序列中获取值

df['ColumnName'].value_counts()[0]
output
4

df['ColumnName'].值计数()[1]
output
2

df['ColumnName'].value_counts()[2]
output
5

或者您可以将输出存储在数据帧中

pd.DataFrame(df['ColumnName'].value_counts())
输出:

     ColumnName
a    4
b    2
c    5

我通常把它保存为一个我感觉更舒服的命令

s = df['ColumnName'].value_counts().to_dict()

{'c': 5, 'a': 4, 'b': 2}

s['b'] #gives 2
可以使用
.keys()
.values()

s = df['ColumnName'].value_counts().to_dict()

{'c': 5, 'a': 4, 'b': 2}

s['b'] #gives 2