我制作了一个csv
文件,如下所示:
现在,在我的Python文件中,我希望它从food field place列中获取数据,这只是:
a
b
c
d
e
然后我希望它只从饮料领域中获取味道等数据。
我的问题是:如何创建一个具有类似"字段"的数据库? (IE:食物/饮料)和每个领域内的地址都是我描述的特定细胞?
答案 0 :(得分:1)
这个问题非常开放,所以我将展示两种可能的方法将这些数据解析成一个可以按照你描述的方式访问的结构。
此代码使用更高级的python和库。它使用csv
读取器周围的生成器来允许有效读取数据的多个部分。然后将数据放入每个部分pandas.DataFrame
。每个数据框都可以在dict中访问。
可以像下列这样访问数据:
ratings['food']['taste']
这将给出pandas.Series
。可以使用常规python列表:
list(ratings['food']['taste'])
使用生成器将数据读取到Pandas Dataframe的代码:
def csv_record_reader(csv_reader):
""" Read a csv reader iterator until a blank line is found. """
prev_row_blank = True
for row in csv_reader:
row_blank = (row[0] == '')
if not row_blank:
yield row
prev_row_blank = False
elif not prev_row_blank:
return
ratings = {}
ratings_reader = csv.reader(my_csv_data)
while True:
category_row = list(csv_record_reader(ratings_reader))
if len(category_row) == 0:
break
category = category_row[0][0]
# get the generator for the data section
data_generator = csv_record_reader(ratings_reader)
# first row of data is the column names
columns = next(data_generator)
# use the rest of the data to build a data frame
ratings[category] = pd.DataFrame(data_generator, columns=columns)
以下是将数据读取到dict
的解决方案。可以通过以下方式访问数据:
ratings['food']['taste']
将CSV读取为dict的代码:
from collections import namedtuple
ratings_reader = csv.reader(my_csv_data)
ratings = {}
need_category = True
need_header = True
for row in ratings_reader:
if row[0] == '':
if not (need_category or need_header):
# this is the end of a data set
need_category = True
need_header = True
elif need_category:
# read the category (food, drink, ...)
category = ratings[row[0]] = dict(rows=[])
need_category = False
elif need_header:
# read the header (place, taste, ...)
for key in row:
category[key] = []
DataEnum = namedtuple('DataEnum', row)
need_header = False
else:
# read a row of data
row_data = DataEnum(*row)
category['rows'].append(row_data)
for k, v in row_data._asdict().items():
category[k].append(v)
测试数据:
my_csv_data = [x.strip() for x in """
food,,
,,
place,taste,day
a,good,1
b,good,2
c,awesome,3
d,nice,4
e,ok,5
,,
,,
,,
drink,,
,,
place,taste,day
a,good,1
b,good,2
c,awesome,3
d,nice,4
e,ok,5
""".split('\n')[1:-1]]
要从文件中读取数据:
with open('ratings_file.csv', 'rb') as ratings_file:
ratings_reader = csv.reader(ratings_file)