我想根据旧字典来创建新字典。我要包括的项目是从特定的索引顺序到另一个特定的索引顺序。
我看到有很多关于基于值或键偷看项目的答案,这不是我想要的。 我有这个字典位于特定行中的pandas DataFrame中,该字典包含用于键的元组和用于值的Id:
{(24, Timestamp('1900-01-01 08:20:48')): '77034', (25, Timestamp('1900-01-01 08:21:47')): '77034', (26, Timestamp('1900-01-01 08:31:25')): '77034', (27, Timestamp('1900-01-01 08:32:11')): '77034', (53, Timestamp('1900-01-01 13:22:51')): '77034', (54, Timestamp('1900-01-01 13:30:40')): '77034', (57, Timestamp('1900-01-01 15:28:25')): '77034', (58, Timestamp('1900-01-01 15:29:32')): '77034', (59, Timestamp('1900-01-01 15:43:55')): '77034', (60, Timestamp('1900-01-01 15:44:46')): '77034', (70, Timestamp('1900-01-01 16:56:44')): '77034', (71, Timestamp('1900-01-01 16:57:41')): '77034', (72, Timestamp('1900-01-01 17:02:57')): '77034', (73, Timestamp('1900-01-01 17:33:29')): '19975', (74, Timestamp('1900-01-01 17:43:56')): '14145', (77, Timestamp('1900-01-01 19:23:26')): '77034'}
到目前为止,我使用的dict理解什么都没有产生。
我希望能够得到这样的东西:
for row in df.itertuples():
df.at[row.Index, 'dict_by_index'] = row.full_dict[13:14]
这将在数据框的新列中产生一个新字典:
{(73, Timestamp('1900-01-01 17:33:29')): '19975', (74, Timestamp('1900-01-01 17:43:56')): '14145'}
答案 0 :(得分:0)
您可以改用它:
df = [{(24, Timestamp('1900-01-01 08:20:48')): '77034'}, {(25, Timestamp('1900-01-01 08:21:47')): '77034'}, {(26, Timestamp('1900-01-01 08:31:25')): '77034'}, {(27, Timestamp('1900-01-01 08:32:11')): '77034'}, {(53, Timestamp('1900-01-01 13:22:51')): '77034'}, {(54, Timestamp('1900-01-01 13:30:40')): '77034'}, {(57, Timestamp('1900-01-01 15:28:25')): '77034'}, {(58, Timestamp('1900-01-01 15:29:32')): '77034'}, {(59, Timestamp('1900-01-01 15:43:55')): '77034'}, {(60, Timestamp('1900-01-01 15:44:46')): '77034'}, {(70, Timestamp('1900-01-01 16:56:44')): '77034'}, {(71, Timestamp('1900-01-01 16:57:41')): '77034'} , {(72, Timestamp('1900-01-01 17:02:57')): '77034'} , {(73, Timestamp('1900-01-01 17:33:29')): '19975'} , {(74, Timestamp('1900-01-01 17:43:56')): '14145'} , {(77, Timestamp('1900-01-01 19:23:26')): '77034'}]
基本上,我将所有这些内容都放在[]
内,然后将每个对象都分成一个独立的对象,所以现在,它不再是字典,而是列表,只要它是列表,它就可以与索引
现在尝试做:
print(df[0])
它将打印第一个对象
{(24, Timestamp('1900-01-01 08:20:48')): '77034'}
您可以执行df[1]
或df[2]
等等,既然已经可以使用索引了,那么您应该会很高兴。
希望这会有所帮助。