擅长:python、mysql、java
<p>这里有一个有效的解决方案,可以给你你想要的结果</p>
<pre><code>df=pd.DataFrame({'customer':['John','Blake','Steph'],'item1':['Apples','Bananas','Oranges'],'item2':['Oranges',np.nan,'Bananas'],'item3':['Bananas',np.nan,np.nan]})
#Get unique items
df=pd.melt(df,id_vars=['customer'])
df2=pd.DataFrame(pd.pivot_table(df,columns='value',index='customer',aggfunc='count').to_records())
df2.columns=['customer','item1','item2','item3']
df2['item1'][df2['item1']==1]='Apples'
df2['item2'][df2['item2']==1]='Bananas'
df2['item3'][df2['item3']==1]='Oranges'
df2
</code></pre>