Skip to main content
 首页 » 编程设计

python之展平 Pandas DataFrame

2024年10月24日12duanxz

我有一个看起来像这样的 Pandas DataFrame(目前除了内置行索引之外没有其他索引,但如果更容易向“Person”和“Car”添加索引,那也很好):

before = pd.DataFrame({ 
  'Email': ['john@example.com','mary@example.com','jane@example.com','john@example.com','mary@example.com'], 
  'Person': ['John','Mary','Jane','John','Mary'], 
  'Car': ['Ford','Toyota','Nissan','Nissan','Ford'] 
}) 

我想重新塑造它看起来像这样:

after = pd.DataFrame({ 
  'Person': ['John','Mary','Jane'], 
  'Email': ['john@example.com','mary@example.com','jane@example.com'], 
  'Ford': [True,True,False], 
  'Nissan': [True,False,True], 
  'Toyota': [False,True,False] 
}) 

请注意,约翰同时拥有一辆福特和一辆尼桑,玛丽拥有一辆福特和一辆丰田,而保罗则一直坚持他信赖的尼桑。

我已经尝试了堆叠多索引 DataFrame、分组、旋转的各种排列——我似乎无法弄清楚如何从“Car”列中获取值并将其转置到一个新列中值“True”,通过名字将人们合并在一起。

请您参考如下方法:

不确定这是否是最好的方法,但一种方法是 -

In [26]: before.pivot_table(index=['Email','Person'],columns=['Car'], aggfunc=lambda x: True).fillna(False).reset_index() 
Out[26]: 
Car             Email Person   Ford Nissan Toyota 
0    jane@example.com   Jane  False   True  False 
1    john@example.com   John   True   True  False 
2    mary@example.com   Mary   True  False   True