【问题标题】:Using pandas index as dictionary key, fill dictionary with values based on matching keys使用 pandas 索引作为字典键,根据匹配键用值填充字典
【发布时间】: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')
  • kproduct_combos 字典中的键值,我将其与 df.... 的 product_id 列进行比较,我想返回 @987654337 @index 作为matches的键值

标签: python pandas dictionary


【解决方案1】:

这里有几个问题。首先,您从enumerate 请求的变量的顺序被切换 - 整数计数器排在第一位:

for i, entry in enumerate(values):
    ...

这就是matches 字典中的键显示为整数的原因。

其次,您仍然需要访问testing_df.indexith 元素才能获得您正在寻找的transaction_id。您可以使用(更正后的)enumerate() 中的 i 执行此操作:

# sample data
transaction_id = ["001","002","003","004","005"]
product_id = {"product_id":[("P01",), ("P01", "P02"), ("P01", "P02", "P09"),
                            ("P01", "P03"), ("P01", "P03", "P05")]}
testing_df = pd.DataFrame(product_id, index=transaction_id)
testing_df.index.name = "transaction_id"

print(testing_df)
                     product_id
transaction_id                 
001                      (P01,)
002                  (P01, P02)
003             (P01, P02, P09)
004                  (P01, P03)
005             (P01, P03, P05)

matches = {}

for i, entry in enumerate(testing_df.product_id):

    # ... some computation ...

    transaction_id = testing_df.index[i]
    recommendation = entry[0] # just as an example
    matches[transaction_id] = recommendation

print(matches)
{'001': 'P01', '002': 'P01', '003': 'P01', '004': 'P01', '005': 'P01'}

【讨论】:

  • TypeError: object of type 'int' has no len()
  • 回想一下,您将 i 放在了错误的位置。现在,i 正确表示循环中的行索引。您需要更新其余代码以反映更正。
猜你喜欢
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多