2 回答
TA贡献1898条经验 获得超8个赞
将值转换为新列,按 过滤第一个日期boolean indexing
,然后按 unpivotDataFrame.melt
和 aggreagate list
:
df['d'] = pd.to_datetime(df['DateTime'], format='(%Y,%m,%d,%H,%M,%S)')
day1 = df['d'].dt.date[0]
df = df[df['d'].dt.date.eq(day1)]
df = df.melt(['DateTime','d'])
df = df[df['value'].eq('Y')]
d = df.groupby('variable')['DateTime'].agg(list).to_dict()
print (d)
{'Facebook': ['(2020,09,01,10,01,00)', '(2020,09,01,10,02,00)', '(2020,09,01,10,03,00)'],
'Instagram': ['(2020,09,01,10,00,00)', '(2020,09,01,10,04,00)', '(2020,09,01,11,00,00)'],
'Twitter': ['(2020,09,01,10,00,00)', '(2020,09,01,10,01,00)', '(2020,09,01,10,04,00)']}
如果需要输出datetime嵌套字典中的每个:
df['d'] = pd.to_datetime(df['DateTime'], format='(%Y,%m,%d,%H,%M,%S)')
df = df.melt(['DateTime','d'])
df = df[df['value'].eq('Y')]
s = df.groupby([df['d'].dt.strftime('%Y-%m-%d'), 'variable'])['DateTime'].agg(list)
print (s)
d1 = {level: s.xs(level).to_dict() for level in s.index.levels[0]}
print (d1)
{'2020-09-01': {'Facebook': ['(2020,09,01,10,01,00)', '(2020,09,01,10,02,00)', '(2020,09,01,10,03,00)'],
'Instagram': ['(2020,09,01,10,00,00)', '(2020,09,01,10,04,00)', '(2020,09,01,11,00,00)'],
'Twitter': ['(2020,09,01,10,00,00)', '(2020,09,01,10,01,00)', '(2020,09,01,10,04,00)']},
'2020-09-02': {'Facebook': ['(2020,09,02,10,00,00)'],
'Instagram': ['(2020,09,02,10,00,00)'],
'Twitter': ['(2020,09,02,10,00,00)']},
'2020-09-03': {'Facebook': ['(2020,09,03,10,00,00)'],
'Instagram': ['(2020,09,03,10,00,00)'],
'Twitter': ['(2020,09,03,10,00,00)']}}
print (d1['2020-09-01'])
{'Facebook': ['(2020,09,01,10,01,00)', '(2020,09,01,10,02,00)', '(2020,09,01,10,03,00)'],
'Instagram': ['(2020,09,01,10,00,00)', '(2020,09,01,10,04,00)', '(2020,09,01,11,00,00)'],
'Twitter': ['(2020,09,01,10,00,00)', '(2020,09,01,10,01,00)', '(2020,09,01,10,04,00)']}
print (d1['2020-09-02'])
{'Facebook': ['(2020,09,02,10,00,00)'], 'Instagram': ['(2020,09,02,10,00,00)'], 'Twitter': ['(2020,09,02,10,00,00)']}
TA贡献1806条经验 获得超8个赞
使用readline逐行读取file.csv。然后你应该将 Instagram 的日期时间(在“Y”的情况下,所以使用 if)收集在一个列表中。对 Facebook 和 Twitter 执行同样的操作。
所以,这是总体方法:
Instagram=[] #make an empty list
for row in file.readlines(): #read line by line of your file
row2=row.split(';') #split elements and make a list with name row2
if str(row2[1])=="Y": Instagram.append(row2[0]) # add date time to instagram list
#do the same for facebook and twitter
print(Instagram)
添加回答
举报