如何在Pandas中基于不同列生成品牌与列的关联统计表?
Got it, let's break this down to get the brand count per column you're looking for. First, let's recap your original data to make sure we're on the same page:
Original User Preference Data
| Users_id | My_Fav | Bro_Fav | Friend_Fav |
|---|---|---|---|
| User0 | BMW | VW | BMW |
| UserA | VW | Mercedes | Honda |
| UserB | Honda | Honda | VW |
| UserC | Mercedes | BMW | Mercedes |
| UserD | VW | BMW | BMW |
Final Brand Count by Column
Here's the aggregated count of each brand across the three columns, exactly as you requested:
| My_Fav | Bro_Fav | Friend_Fav | |
|---|---|---|---|
| BMW | 1 | 2 | 2 |
| VW | 2 | 1 | 1 |
| Honda | 1 | 1 | 1 |
| Mercedes | 1 | 1 | 1 |
How to Calculate This (Manual + Automated)
Manual Method
If you're doing this by hand, just tally each brand's appearance in every column:
- BMW: Shows up once in
My_Fav(User0), twice inBro_Fav(UserC, UserD), and twice inFriend_Fav(User0, UserD) - VW: Appears twice in
My_Fav(UserA, UserD), once inBro_Fav(User0), and once inFriend_Fav(UserB) - Honda: One occurrence in each column (
My_Fav: UserB,Bro_Fav: UserB,Friend_Fav: UserA) - Mercedes: One occurrence in each column (
My_Fav: UserC,Bro_Fav: UserA,Friend_Fav: UserC)
Automated Method (For Larger Datasets)
If you have more data later, using Python's pandas library will save you time. Here's a quick script to generate the same result:
import pandas as pd # Load your data into a DataFrame user_data = { 'Users_id': ['User0', 'UserA', 'UserB', 'UserC', 'UserD'], 'My_Fav': ['BMW', 'VW', 'Honda', 'Mercedes', 'VW'], 'Bro_Fav': ['VW', 'Mercedes', 'Honda', 'BMW', 'BMW'], 'Friend_Fav': ['BMW', 'Honda', 'VW', 'Mercedes', 'BMW'] } df = pd.DataFrame(user_data) # Calculate counts for each column brand_counts = pd.DataFrame({ column: df[column].value_counts() for column in ['My_Fav', 'Bro_Fav', 'Friend_Fav'] }).fillna(0).astype(int) # Print or display the result print(brand_counts)
Running this script will output the exact count table you need—no manual tallying required!
内容的提问来源于stack exchange,提问作者s_khan92
相关产品推荐
相关产品推荐

