压平Pandas数据帧

2024-03-28 10:51:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Pandas数据帧,如下所示(目前除了内置的行索引外没有索引,但是如果向“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']
})

我想把它改成这样:

^{pr2}$

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

我尝试过各种不同的排列方式来堆叠一个多索引的数据帧、分组、旋转——我似乎不知道如何从“Car”列中获取值,并将其转换为一个值为“True”的新列,通过,比如说,他们的名字来将人合并在一起。在


Tags: 数据compandasexamplejohncar内置person
2条回答
before['has_car'] = True

Out[93]:
car                Email    Person  has_car
Ford    john@example.com    John    True
Toyota  mary@example.com    Mary    True
Nissan  jane@example.com    Jane    True
Nissan  john@example.com    John    True
Ford    mary@example.com    Mary    True

df = before.pivot_table(index = ['Person' , 'Email'], columns= 'Car' , values='has_car')


Out[89]:
                            Ford    Nissan  Toyota
Person  Email           
Jane    jane@example.com    NaN     True    NaN
John    john@example.com    True    True    NaN
Mary    mary@example.com    True    NaN     True

df.fillna(False).reset_index()

Out[102]:
Car Person  Email               Ford    Nissan  Toyota
0   Jane    jane@example.com    False   True    False
1   John    john@example.com    True    True    False
2   Mary    mary@example.com    True    False   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

相关问题 更多 >