首页 > 解决方案 > 统计特定列中的重复项

问题描述

惠。我是一个新的 Python 用户。我需要编写一些脚本来从特定的 .txt 文件中提取数据。文件中的数据是:

Milo    12345678901234  DN127   POTATO_123_456  
Milo    12345678901234  DN127   POTATO_123_456
Lamb    12345678901307  DN127   TOMATO_123_456
Lamb    12345678901618  DN127   TOMATO_123_456
Lamb    12345678901953  DN127   TOMATO_123_456
Milo    12345678902213  DN127   CHILI_789_0126  
Milo    12345678902822  DN127   BANANA_134-123  

脚本会做的是,它只会显示包含单词“Milo”的行,并计算第 4 列(第 3 列)中的重复项。我设法用“Milo”一词显示该行,但不知道如何计算第 8 列中的重复词。这是我到目前为止所做的:

with open ("food.txt") as food:
                for line in food:
                    if line.find("\tMilo")!=-1:
                        print(line)

标签: pythoncountcounterrepeat

解决方案


使用熊猫:

df = pandas.read_csv('food.txt', sep = " ", header = None)
df.columns = ['Product', 'ID', 'Another ID', 'Some Code']

df = df[df['Product'].isin(['Milo'])]
df['Count of Repetitive Some Code'] = df.groupby('Some Code')['Some Code'].transform('count')

传奇:

Product是你的专栏Milo, etc

ID是你的专栏12345678901234, etc

Another ID是你的专栏DN127, etc

Some Code是您的列,POTATO_123_456, etc==> 是您要计算的列。


推荐阅读