我的数据集如下所示:
W000000457,,
,9/18/2016 11:28,37
,4/21/2016 0:07,54
,11/5/2016 12:05,42
,7/14/2016 15:43,54
W000000457 - Count,,100
2069320,,
,12/10/2016 0:22,12
,9/25/2016 14:07,28
,1/24/2016 6:54,59
2069320 - Count,,100
111,,
,1/16/2016 10:25,58
,6/11/2016 4:17,43
,4/21/2016 7:56,47
,3/17/2016 3:48,20
111 - Count,,100
列是ID,日期,值。我做了两次主要的清洁/按摩数据。
1)使用第1行中的ID,我填充以下行 2)删除所有行" Count"在行[0]
中我的目标是得到这样的东西:
W000000457,9/18/2016 11:28,37
W000000457,4/21/2016 0:07,54
W000000457,11/5/2016 12:05,42
W000000457,7/14/2016 15:43,54
2069320,12/10/2016 0:22,12
2069320,9/25/2016 14:07,28
2069320,1/24/2016 6:54,59
111,1/16/2016 10:25,58
111,6/11/2016 4:17,43
111,4/21/2016 7:56,47
111,3/17/2016 3:48,20
这是我到目前为止的代码:
import csv
with open('data.txt','rb') as f_in:
reader = csv.reader(f_in)
row = next(reader)
last_row = row
for row in reader:
row = [x if x else y for x, y in zip(row, last_row)]
if 'COUNT' not in row[0].upper():
print row
last_row = row
这让我接近但问题是处理不同ID的例子中的记录:
W000000457,,
,1/24/2016 6:54,59
2069320 - Count,,100
111,,
,1/16/2016 10:25,58
将成为(使用我的代码):
W000000457,1/24/2016 6:54,59
111,1/24/2016 6:54,100
111,1/16/2016 10:25,58
ID 111的第一个实例不是从先前现有值携带的实际值。
或者在上面的例子中我得到:
W000000457,9/18/2016 11:28,37
W000000457,4/21/2016 0:07,54
W000000457,11/5/2016 12:05,42
W000000457,7/14/2016 15:43,54
**2069320,7/14/2016 15:43,100**
2069320,12/10/2016 0:22,12
2069320,9/25/2016 14:07,28
2069320,1/24/2016 6:54,59
**111,1/24/2016 6:54,100**
111,1/16/2016 10:25,58
111,6/11/2016 4:17,43
111,4/21/2016 7:56,47
111,3/17/2016 3:48,20
**中的字段是假值
关于我应该如何处理的任何想法?
我正在考虑删除每个ID的第一个实例,或者寻找一种方法来替换我的csvreader的[0]而不是每个字段。
答案 0 :(得分:1)
使用csv类型数据时,请使用pandas。
阅读数据:
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO('''W000000457,,
,9/18/2016 11:28,37
,4/21/2016 0:07,54
,11/5/2016 12:05,42
,7/14/2016 15:43,54
W000000457 - Count,,100
2069320,,
,12/10/2016 0:22,12
,9/25/2016 14:07,28
,1/24/2016 6:54,59
2069320 - Count,,100
111,,
,1/16/2016 10:25,58
,6/11/2016 4:17,43
,4/21/2016 7:56,47
,3/17/2016 3:48,20
111 - Count,,100'''), names=['col1', 'col2', 'col3'])
在第一列中转发填充NaN项目:
df['col1'] = df['col1'].fillna(method='ffill')
过滤掉第一列包含' Count'
的项目df = df[~df['col1'].str.contains('Count')]
删除仍有NaN的行:
df = df.dropna()
最终结果:
col1 col2 col3
1 W000000457 9/18/2016 11:28 37.0
2 W000000457 4/21/2016 0:07 54.0
3 W000000457 11/5/2016 12:05 42.0
4 W000000457 7/14/2016 15:43 54.0
7 2069320 12/10/2016 0:22 12.0
8 2069320 9/25/2016 14:07 28.0
9 2069320 1/24/2016 6:54 59.0
12 111 1/16/2016 10:25 58.0
13 111 6/11/2016 4:17 43.0
14 111 4/21/2016 7:56 47.0
15 111 3/17/2016 3:48 20.0