After doing df.['ColumnName'].value_counts()
to count unique strings in a column of a data frame, I get results in the following format:
a 4
b 2
c 5
Name: ColumnName, dtype: int64
How can I extract values from these results? For example, how can I get 'b' or 2?
It is Series
, so use methods Series.at
, Series.iat
, Series.loc
, Series.iloc
:
s = df['ColumnName'].value_counts()
Test :
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
You could use index to get the values from the series, for example
df['ColumnName'].value_counts()[0]
output 4
df['ColumnName'].value_counts()[1]
output 2
df['ColumnName'].value_counts()[2]
output 5
Or you could store the output in a DataFrame
pd.DataFrame(df['ColumnName'].value_counts())
output:
ColumnName
a 4
b 2
c 5
I generally save it as a dict which I feel more comfortable manipulating
s = df['ColumnName'].value_counts().to_dict()
{'c': 5, 'a': 4, 'b': 2}
s['b'] #gives 2
Can get keys, values using .keys()
, .values()
to extract values
from df['ColumnName'].value_counts():
df['ColumnName'].value_counts().values.tolist()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.