pandas - 对所有结果进行分组而不采取任何措施
问题描述
在 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
解决方案
您可以尝试这段代码而不是直接的 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.
推荐阅读
- git - 如何测试 git pull 的结果?
- mysql - 如何使用 Mysql 或 postman 将数据从一个表复制到另一个现有表?
- sql - “创建非聚集索引”,那是什么以及如何创建?
- json - Swift 中的异步 JSON 请求
- laravel-5.7 - 如何覆盖供应商服务提供商使用的供应商特征?
- dynamics-crm - Dynamics 365,UCI - 找不到编辑新表单行为的方法
- javascript - 如何从数组中获得独特的年份?
- python - bash:从python脚本向进程发送信号
- amazon-web-services - 如何使用 API 网关进行身份验证?
- postgresql - 1892 年之前的 postgresql 中时区错误的时间戳