[英]Create a dictionary of unique values of a column in a dataframe in pandas
[英]Creating Dictionary from Pandas DataFrame Column Based on Unique Values in Column
我有个头疼的问题,我不确定是否可以用一两行代码来解决。 我可以或多或少地在没有数据帧的情况下做到这一点(例如,如果数据只是.txt),但是我想看看它是否可以通过熊猫来完成。
下面是df.head(10)
,我想创建一个字典,其中的键是解析的唯一day_of_week
数字(对于周日至周六,为1-7),其值是在每个键上发生的births
总数单个day_of_week
值的。
year month date_of_month day_of_week births
0 1994 1 1 6 8096
1 1994 1 2 7 7772
2 1994 1 3 1 10142
3 1994 1 4 2 11248
4 1994 1 5 3 11053
5 1994 1 6 4 11406
6 1994 1 7 5 11251
7 1994 1 8 6 8653
8 1994 1 9 7 7910
9 1994 1 10 1 10498
我可以使用以下命令轻松为各个day_of_week
值创建SUM:
df.groupby[df['day_of_week'] == 1, 'births'].sum()
将所有在day_of_week == 1
上发生的出生day_of_week == 1
。 我可以使用以下命令创建一个day_of_week
值的字典:
d = {i : 0 for i in df['day_of_week']}
产生字典d
:
{1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0}
但是我无法将两者连接起来,所以我可以解析day_of_week
数字,将这些数字分配给字典的键 ,然后对每个day_of_week
上发生的births
进行求和,然后将这些总和值分配给其各自的键。
如果有人有建议! 我在下面创建了一个虚拟数据框,用于复制条件(如果有帮助的话),因为day_of_week
值确实会在我的数据框中重复(尽管您无法从df.head()
)。
d = {'day_of_week' : pd.Series([1, 6, 6, 5, 3, 2, 6, 4, 4, 7, 1]),
'births' : pd.Series([5544, 23456, 473, 34885, 3498, 324, 6898, 83845, 959, 8923, 39577])}
df_dummy = pd.DataFrame(d)
好像你需要
df_dummy.set_index('day_of_week').births.sum(level=0).to_dict()
Out[30]: {1: 45121, 2: 324, 3: 3498, 4: 84804, 5: 34885, 6: 30827, 7: 8923}
可以肯定地用熊猫来回答这一问题。 只需使用groupby构造对您所解析的一周中的某天进行分组,然后对出生数求和。 Pandas内置了将其转换为字典的功能,其中您的键是星期几,值是总和:
import pandas as pd
day_of_week = [6, 7, 1, 2, 3, 4, 5, 6, 7, 1]
births = [8096, 7772, 10142, 11248, 11053, 11406, 11251, 8653, 7910, 10498]
df = pd.DataFrame({'day_of_week': day_of_week,
'births': births})
df.groupby('day_of_week')['births'].sum().to_dict()
# output: {1: 20640, 2: 11248, 3: 11053, 4: 11406, 5: 11251, 6: 16749, 7: 15682}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.