You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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_idMy_FavBro_FavFriend_Fav
User0BMWVWBMW
UserAVWMercedesHonda
UserBHondaHondaVW
UserCMercedesBMWMercedes
UserDVWBMWBMW

Final Brand Count by Column

Here's the aggregated count of each brand across the three columns, exactly as you requested:

My_FavBro_FavFriend_Fav
BMW122
VW211
Honda111
Mercedes111

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 in Bro_Fav (UserC, UserD), and twice in Friend_Fav (User0, UserD)
  • VW: Appears twice in My_Fav (UserA, UserD), once in Bro_Fav (User0), and once in Friend_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 07:19:04