首页 > 解决方案 > 对所有结果进行分组而不采取任何措施

问题描述

在 groupby 中排序并不像我想象的那样工作。在下面的示例中,我不想将“USA”组合在一起,因为只有一行“Russia”。

from io import StringIO

myst="""india, 905034 , 19:44   
USA, 905094  , 19:33
Russia,  905154 ,   21:56
USA, 345345, 45:55
USA, 34535, 65:45
"""
u_cols=['country', 'index', 'current_tm']

myf = StringIO(myst)
import pandas as pd
df = pd.read_csv(StringIO(myst), sep=',', names = u_cols)

当我使用 groupby 时,我得到以下信息:

df.groupby('country', sort=False).size()

country
india     1
USA       3
Russia    1
dtype: int64

无论如何我可以得到这样的结果......

country
india     1
USA       1
Russia    1
USA       2

标签: pandas

解决方案


您可以尝试这段代码而不是直接的 groupby:

country = [] #initialising lists
count = []
for i, g in df.groupby([(df.country != df.country.shift()).cumsum()]): #Creating a list that increases by 1 for every time a unique value appears in the dataframe country column.
    country.append(g.country.tolist()[0]) #Adding the name of country to list.
    count.append(len(g.country.tolist())) #Adding the number of times that country appears to list.

pd.DataFrame(data = {'country': country, 'count':count}) #Binding the lists all into a dataframe.

这将df.groupby([(df.country != df.country.shift()).cumsum()])创建一个数据框,该数据框为国家列中的每个国家/地区更改提供一个唯一编号(累积)。

在 for 循环中,i代表分配给每个国家/地区外观的唯一累积数字,并g代表原始数据框中的相应完整行。

g.country.tolist()输出每个独特外观(aka)的国家名称列表,i

['india']
['USA']
['Russia']
['USA', 'USA']

对于您给定的数据。

因此,第一项是国名,长度代表出现次数。然后可以将此信息(记录在列表中,然后)放在一个数据框中并提供您需要的输出。

您还可以使用列表推导而不是 for 循环:

cumulative_df = df.groupby([(df.country != df.country.shift()).cumsum()]) #The cumulative count dataframe
country = [g.country.tolist()[0]  for i,g in  cumulative_df] #List comprehension for getting country names.
count = [len(g.country.tolist())  for i,g in  cumulative_df] #List comprehension for getting count for each country.

参考:Pandas DataFrame:如何对连续值进行分组


推荐阅读