Python-根据条件读取文本文件中的特定行 - python

问题陈述:

我有一个如下文件。

name | date | count
John | 201406 | 1
John | 201410 | 2
Mary | 201409 | 180
Mary | 201410 | 154
Mary | 201411 | 157
Mary | 201412 | 153
Mary | 201501 | 223
Mary | 201502 | 166
Mary | 201503 | 163
Mary | 201504 | 169
Mary | 201505 | 157
Tara | 201505 | 2

该文件显示了约翰,玛丽和塔拉三个人两个月的计数数据。我想分析这些数据并为每个人提供一个状态标签,即活跃,不活跃或新来的人。

如果某人具有201505和其他前几个月的条目,则他们是活跃的-例如Mary

如果某人没有201505的条目,那么他就处于非活动状态,例如John

一个人是新来的,如果他们仅在201505年有1个条目(例如Tara)。

此外,如果一个人很活跃,我想获得他们最近5个计数的中位数。例如,对于玛丽,我希望得到的平均值为((157 + 169 + 163 + 166 + 223 + 5)。

题:

我想了解如何在Python 2.7中读取此文件,以满足我的要求。我从以下内容开始,但不确定如何获取特定人员的先前条目(即文件中的先前行)。

for line in data:
    col = line.split('\t')
    name = col[0]
    date = col[1]
    count = col[2]

python大神给出的解决方案

import pandas as pd:
df = pd.read_csv('input_csv.csv') # This assumes you have a csv format file
names = {}
for name, subdf in df.groupby('name'):
    if name not in names:
        names[name] = {}
    if (subdf['date']==201505).any():
        if subdf['count'].count()==1:
            names[name]['status'] = 'new'
        else:
            names[name]['status'] = 'active'
            names[name]['last5median'] = subdf['count'].tail().median()
    else:
        names[name]['status'] = 'inactive'


>>>
{'John': {'status': 'inactive'},
 'Mary': {'last5median': 166.0, 'status': 'active'},
 'Tara': {'status': 'new'}}