Python 熊猫:从dataframe创建json文件
我有数据帧Python 熊猫:从dataframe创建json文件,python,json,pandas,Python,Json,Pandas,我有数据帧 ID, visiting 111, 03.2015 111, 07.2015 111, 05.2016 222, 12.2013 222, 04.2016 333, 02.2014 333, 06.2015, 333, 11.2015 我需要像这样获取文件(我需要指定从2013年12月到2016年6月的所有月份) 我怎样才能从熊猫那里得到它呢?使用groupbys会更有效,但这样就完成了任务: txt = """ID, visiting 111, 03.2015 111, 07.2
ID, visiting
111, 03.2015
111, 07.2015
111, 05.2016
222, 12.2013
222, 04.2016
333, 02.2014
333, 06.2015,
333, 11.2015
我需要像这样获取文件(我需要指定从2013年12月到2016年6月的所有月份)
我怎样才能从熊猫那里得到它呢?使用
groupby
s会更有效,但这样就完成了任务:
txt = """ID, visiting
111, 03.2015
111, 07.2015
111, 05.2016
222, 12.2013
222, 04.2016
333, 02.2014
333, 06.2015
333, 11.2015"""
split = [line.split(', ') for line in txt.split('\n')]
df = pd.DataFrame(split[1:], columns=split[0])
results = {}
for ID in df.ID.unique():
results[ID] = {}
for year in range(2013, 2017):
if year == 2013:
months = [12]
elif year == 2016:
months = range(1, 7)
else:
months = range(1, 13)
for month in months:
search_text = '{:02d}.{}'.format(month, year)
result_text = '{}-{:02d}'.format(year, month)
for ID in df.ID.unique():
if len(df[(df.ID == ID)&(df.visiting == search_text)]) > 0:
boolean = 1
else:
boolean = 0
results[ID][result_text] = boolean
import json
results = json.dumps(results)
txt = """ID, visiting
111, 03.2015
111, 07.2015
111, 05.2016
222, 12.2013
222, 04.2016
333, 02.2014
333, 06.2015
333, 11.2015"""
split = [line.split(', ') for line in txt.split('\n')]
df = pd.DataFrame(split[1:], columns=split[0])
results = {}
for ID in df.ID.unique():
results[ID] = {}
for year in range(2013, 2017):
if year == 2013:
months = [12]
elif year == 2016:
months = range(1, 7)
else:
months = range(1, 13)
for month in months:
search_text = '{:02d}.{}'.format(month, year)
result_text = '{}-{:02d}'.format(year, month)
for ID in df.ID.unique():
if len(df[(df.ID == ID)&(df.visiting == search_text)]) > 0:
boolean = 1
else:
boolean = 0
results[ID][result_text] = boolean
import json
results = json.dumps(results)