私は、ユーザ、各ユーザが購入した製品、および製品の価格で構成される大きなパンダのデータフレームを持っています。パンダのデータフレームグループの高速反復変更
私が使用しているコードを以下に示します。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
# Create Dataframe randomly
product_list = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9', 'P10', 'P11', 'P12']
user_list = ['U1', 'U2', 'U3', 'U4', 'U5', 'U6', 'U7', 'U8', 'U9', 'U10']
price_list = [50, 90, 100]
# Create random transactions
transactions = pd.DataFrame(np.random.choice(user_list, 200))
transactions['item'] = pd.DataFrame(np.random.choice(product_list, 200))
transactions['quantity'] = 1
transactions['price'] = np.random.choice([50, 90, 100], 200)
transactions.columns = ['user', 'item', 'quantity', 'price']
transactions['suggested_price'] = 0
# Create groups to apply suggested discount
grouped = transactions.groupby(["user", "item"])
# Apply suggested discount
for key, group in grouped:
transactions.set_value(
group.index, 'suggested_discount', np.random.random())
私の最大の問題は、各ユーザー(顧客)に推奨割引を適用する最後のコードブロックのパフォーマンスです。元のデータフレームは600万行以上あります。このコード行の前に他のステップがあり、元のコードでは
transactions.set_value(
group.index, 'suggested_discount', np.random.random())
:
また、私は気づいた一つのことは、私はグループの値、すなわち、行を変更したときに最も遅いステップがあるということです。
グループ列の値を変更するのが遅いとは思っていませんでした。より良い、より速い実装がありますか?
ありがとうございます!