Python 使用pandas重新排列数据帧
我得到了以下数据帧:Python 使用pandas重新排列数据帧,python,dataframe,Python,Dataframe,我得到了以下数据帧: import pandas as pd test = pd.DataFrame([["Bugatti","Veyron"], ["Bugatti","Chiron"], ["VW","Golf"], ["VW","Passat"], ["VW","Polo"], ["
import pandas as pd
test = pd.DataFrame([["Bugatti","Veyron"],
["Bugatti","Chiron"],
["VW","Golf"],
["VW","Passat"],
["VW","Polo"],
["VW","Caddy"],
["Porsche","Taycan"],
["Porsche","911"]],
columns=['Brand', 'Model'])
test
我想更改它,以便您将品牌作为(布加迪、大众、保时捷)作为列标题,并在其下方的列中显示车型。当然,这只是一个更大列表的例子。有没有一种快速的方法来重新排列数据帧?之后应该是这样的
Bugatti VW Porsche
Veyron Golf Taycan
Chiron Passat 911
Polo
Caddy
你可以尝试转置或旋转。转置将为同一品牌提供多个列。而pivot在结果中将具有空值 转置:
test.T
结果
Brand Bugatti Bugatti VW VW VW VW Porsche Porsche
Model Veyron Chiron Golf Passat Polo Caddy Taycan 911
支点:
test.pivot(columns='Brand',values='Model')
结果
Bugatti Porsche VW
Veyron NaN NaN
Chiron NaN NaN
NaN NaN Golf
NaN NaN Passat
NaN NaN Polo
NaN NaN Caddy
NaN Taycan NaN
NaN 911 NaN
提供预期output@akshaynevrekar对不起,我完全忘了。现在换了。谢谢,看起来已经很不错了。现在有没有办法去掉空值?