Jam*_*ips 53 python series dataframe pandas
假设我们使用了熊猫的dataframe[column].value_counts()输出:
apple 5
sausage 2
banana 2
cheese 1
Run Code Online (Sandbox Code Playgroud)
如何按上面显示的顺序从中提取值,例如max to min?
[apple,sausage,banana,cheese]
Mik*_*ler 80
试试这个:
dataframe[column].value_counts().index.tolist()
['apple', 'sausage', 'banana', 'cheese']
Run Code Online (Sandbox Code Playgroud)
Mar*_*oma 25
#!/usr/bin/env python
import pandas as pd
# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
(2, 'France'),
(3, 'Indonesia'),
(4, 'France'),
(5, 'France'),
(6, 'Germany'),
(7, 'UK'),
],
columns=['groupid', 'country'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()
Run Code Online (Sandbox Code Playgroud)
现在,print(df['country'].value_counts())给出:
France 3
Germany 2
UK 1
Indonesia 1
Run Code Online (Sandbox Code Playgroud)
并print(values)给出:
['France', 'Germany', 'UK', 'Indonesia']
Run Code Online (Sandbox Code Playgroud)
并print(counts)给出:
[3, 2, 1, 1]
Run Code Online (Sandbox Code Playgroud)
Saw*_*ant 16
如果有人在评论中错过了它,试试这个:
dataframe[column].value_counts().to_frame()
Run Code Online (Sandbox Code Playgroud)
提取值的最佳方法是执行以下操作
json.loads(dataframe[column].value_counts().to_json())
Run Code Online (Sandbox Code Playgroud)
这将返回一个字典,您可以像使用任何其他字典一样使用它。使用值或键。
{"apple": 5, "sausage": 2, "banana": 2, "cheese": 1}
Run Code Online (Sandbox Code Playgroud)