좋은 저녁, 모두가 코로나에서 안전하고 안전하기를 바랍니다. 두 개의 Csv 파일이 있습니다. history.csv-> 제품 및 customerId를 포함하고 다른 CSV customers.csv에는 history.csv에있는 모든 customerId가 포함됩니다. 각 고객이 제품을 몇 번 구입했는지 알고 싶습니다. 예를 들면 :
product 3344 is bought 3 times by userID 2, product 3321 bought 1 time by userID 2.
모든 사용자를 찾고 싶습니다. 아래는 내 코드이며 사용자가 아닙니다.
get_count = pd.melt(part_with_no_count.set_index('customerId')['products'].apply(pd.Series).reset_index(),
id_vars=['customerId'],
value_name='products') \
.dropna().drop(['variable'], axis=1) \
.groupby(['customerId', 'products']) \
.agg({'products': 'count'}) \
.rename(columns={'products': 'product_count'}) \
.reset_index() \
.rename(columns={'products': 'productId'})
get_count.to_csv("output/part_number_1_with_count.csv", index=False)
history.csv의 샘플 데이터 :
products,customerId
27845,22986
39275,142175
43251,200540
42900,69496
21472,178294
37067,150285
4945,205945
17333,47461
38739,123967
46979,59203
436,105341
예상 출력 (예) :
customerId,productId,product_count
21,24186,1
28,25949,1
31,12962,1
31,26246,1
38,26683,1
43,1667,1
50,10831,1
54,47752,1
샘플 df
print(df)
products customerId
0 27845 22986
1 39275 142175
2 43251 200540
3 42900 69496
4 21472 178294
5 37067 150285
6 4945 205945
7 17333 47461
8 38739 123967
9 46979 59203
10 436 105341
해결책
df_count = (df.groupby('customerId')['products']
.value_counts()
.rename('product_count')
.reset_index())
print(df_count)
customerId products product_count
0 22986 27845 1
1 47461 17333 1
2 59203 46979 1
3 69496 42900 1
4 105341 436 1
5 123967 38739 1
6 142175 39275 1
7 150285 37067 1
8 178294 21472 1
9 200540 43251 1
DataFrame df
은 어디에 History
있습니까?
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다