熊猫:我可以按一列的条目分组并根据另一列的条目求和元素

时间:2019-03-16 12:29:30

标签: python-3.x pandas pandas-groupby

我有以下数据框

index =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
dct =  {'Unique household identifier': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 2}, 'Relationship to head [Standardized version]': {0: 'Head', 1: 'Spou', 2: 'Son/', 3: 'Son/', 4: 'Son/', 5: 'Son/', 6: 'Head', 7: 'Spou', 8: 'Son/', 9: 'Son/'}}
R = pd.DataFrame( dct, index=index )

enter image description here

我想转换这个DataFrame(假设它还有很多其他列)。我正在尝试使其外观为

enter image description here

我尝试使用以下代码在for循环和数据透视表中对此进行编码,但是没有用。

第一个:

R.pivot(index='Unique household identifier', columns='Relationship to head [Standardized version]', values='Relationship to head [Standardized version]')

第二个:

B=[]
for i in range(1,len(R.columns)+1):
    A=R[(R['Unique household identifier']==i)*(R['Relationship to head [Standardized version]']!='Head')]['Relationship to head [Standardized version]'].value_counts()
    B.append(pd.DataFrame(data=[A.values],columns=A.index))

1 个答案:

答案 0 :(得分:1)

一个解决方案可能是json.loads(soup.find("script", type="application/ld+json").text)

pd.crosstab