我有以下数据帧
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 )

我想转换这个DataFrame (假设它有很多其他列)。我试着让它看起来像是

我尝试使用以下代码使用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))发布于 2019-03-17 00:13:57
一种解决方案可能是pd.crosstab
res = pd.crosstab(index=R['Unique household identifier'],
columns=R['Relationship to head [Standardized version]'])
res.drop('Head', axis=1)
Relationship to head [Standardized version] Son/ Spou
Unique household identifier
1 4 1
2 2 1https://stackoverflow.com/questions/55196775
复制相似问题