2024-05-29 11:46:19 发布
网友
我有数据帧
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会更有效,但这样可以完成任务:
groupby
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)
使用
groupby
s会更有效,但这样可以完成任务:相关问题 更多 >
编程相关推荐