【发布时间】:2017-08-05 19:37:44
【问题描述】:
我有一个test_df 组织如下:
[in]
# Use the arrays to create a dataframe
testing_df =pd.DataFrame(test_array,columns=['transaction_id','product_id'])
# Split the product_id's for the testing data
testing_df.set_index(['transaction_id'],inplace=True)
print(testing_df.head(n=5))
[out]
product_id
transaction_id
001 (P01,)
002 (P01, P02)
003 (P01, P02, P09)
004 (P01, P03)
005 (P01, P03, P05)
然后我对其进行了一些计算并创建了一个字典来存储结果:
# Initialize a dictionary to store the matches
matches = {}
# Return the product combos values that are of the appropriate length and the strings match
for transaction_id,i in enumerate (testing_df['product_id']):
recommendation = None
recommended_count = 0
for k, count in product_combos.items():
k = list(k)
if len(i)+1 == len(k) and count >= recommended_count:
for product in i:
if product in k:
k.remove(product)
if len(k) == 1:
recommendation = k[0]
recommended_count = count
matches[transaction_id] = recommendation
print(matches)
[out]
{0: 'P09', 1: 'P09', 2: 'P06', 3: 'P09', 4: 'P09', 5: 'P09'}
我遇到的问题是 matches 字典的键应该是 001,002,003,004,005 等 - 对应于 test_df 的索引,即 001-100。
我遇到的第二个问题是我想用 001-100 的键填充另一个字典 (recommendations)。我想通过匹配键值将matches 中的值填充到这个字典中。
【问题讨论】:
-
先尝试将键转换为字符串。如果这不起作用,请执行
str(key).rjust(3, '0') -
这不起作用,当我将其更改为
k = list(str(k))时,整个字典都变空了 -
什么是
k?我假设这是一个整数 ID。我不知道product_combos是什么。如果您想将整个索引系列转换为带有前导 3 0 的字符串,您可以执行df.index.astype(str).str.rjust(3, '0') -
k是product_combos字典中的键值,我将其与 df.... 的product_id列进行比较,我想返回 @987654337 @index 作为matches的键值
标签: python pandas dictionary