如果多次使用密钥,如何从数据框创建字典?
How to create a dictionary from a dataframe if the key is used multiple times?
我有一个包含日期、代码和收盘价的数据框
有些行具有相同的日期
key= date value= ticker value close
import pandas as pd
data = {'Ticker': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
'close': [1200, 150, 300, 450, 200]
}
df = pd.DataFrame(data, index=
['27/01/2022','27/01/2022','25/01/2022','24/01/2022','23/01/2022'])
df
Ticker close
27/01/2022 laptop 1200
27/01/2022 printer 150
25/01/2022 tablet 300
24/01/2022 desk 450
23/01/2022 chair 200
我正在尝试获取如下所示的字典
Key
27/01/2022 laptop : 1200, printer : 150
25/01/2022 tablet : 300
24/01/2022 desk 450
23/01/2022 chair 200
正如 baileythegreen 在评论中提到的那样,您的样本输出不是有效的字典。如果你想要输出
{'23/01/2022': {'chair': 200},
'24/01/2022': {'desk': 450},
'25/01/2022': {'tablet': 300},
'27/01/2022': {'laptop': 1200, 'printer': 150}}
你可以做到
{date: dict(zip(sub_df['Ticker'], sub_df['close']))
for date, sub_df in df.groupby(df.index)}
我有一个包含日期、代码和收盘价的数据框 有些行具有相同的日期
key= date value= ticker value close
import pandas as pd
data = {'Ticker': ['laptop', 'printer', 'tablet', 'desk', 'chair'],
'close': [1200, 150, 300, 450, 200]
}
df = pd.DataFrame(data, index=
['27/01/2022','27/01/2022','25/01/2022','24/01/2022','23/01/2022'])
df
Ticker close
27/01/2022 laptop 1200
27/01/2022 printer 150
25/01/2022 tablet 300
24/01/2022 desk 450
23/01/2022 chair 200
我正在尝试获取如下所示的字典
Key
27/01/2022 laptop : 1200, printer : 150
25/01/2022 tablet : 300
24/01/2022 desk 450
23/01/2022 chair 200
正如 baileythegreen 在评论中提到的那样,您的样本输出不是有效的字典。如果你想要输出
{'23/01/2022': {'chair': 200},
'24/01/2022': {'desk': 450},
'25/01/2022': {'tablet': 300},
'27/01/2022': {'laptop': 1200, 'printer': 150}}
你可以做到
{date: dict(zip(sub_df['Ticker'], sub_df['close']))
for date, sub_df in df.groupby(df.index)}