Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-根据条件读取文本文件中的特定行_Python_File_Line_Readfile - Fatal编程技术网

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

Python-根据条件读取文本文件中的特定行,python,file,line,readfile,Python,File,Line,Readfile,问题陈述: 我有一个文件如下 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

问题陈述:

我有一个文件如下

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的条目,就像塔拉一样,那么他就是新来的

此外,如果一个人是活跃的,我想得到他们最近的5次计数的中位数。例如,对于Mary,我希望得到的平均值为((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]

我认为你可以用dict解决你的问题

import re

spl = """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"""

dicto = {}

listo = re.split("\\||\n",spl)
listo = [x.strip() for x in listo]
for x in range(3,len(listo),3):
    try:
        dicto[listo[x]].append([listo[x+1],listo[x+2]])
    except KeyError:
        dicto[listo[x]]= []
        dicto[listo[x]].append([listo[x+1],listo[x+2]])

print (dicto.get('John'))
输出:

[['201406', '1'], ['201410', '2']]

因此,现在您有了所有的数据,对于您的dict of dict中的所有用户,您可以对他们做您想做的事情

考虑使用
Pandas
,然后您可以使用
.groupby('name')
函数单独查看每个人。这是否假设我们在txt文件中有一个标题行?没有头文件的情况如何?是的,这假定文件有头行。如果没有标题,并且您希望显式提供列名,请按如下方式读取文件:
df=pd.read\u csv('input\u csv.csv',name=['name'、'date'、'count'])
谢谢。我们在哪里告诉程序只获取名称[name]['last5median']=subdf['count'].tail().median()中最后5个的中间值?如果我想要最后8个条目呢?
.tail()
部分返回最后5个条目(5是tail的默认值)。例如,如果你想要8,你可以做
.tail(8)
。你明白了。中位数是使用
.media()
部分来计算的,您在
.tail(X)
中给出了最后X个条目。很高兴它有帮助!希望这能回答您的问题。如果我的源文件是以制表符分隔的文本文件,我将如何将其读入变量spl,以及re.split函数将如何更改?谢谢
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'}}