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

在Pandas DataFrame中按索引替换列表值生成新字段

Here's a straightforward way to create your new_values column by leveraging Pandas' apply() function with custom list replacement logic:

Step-by-Step Implementation

1. Set Up Sample DataFrame (for testing)

First, let's replicate your input data to verify the solution:

import pandas as pd

data = {
    'flat_values': [[20, None, None, None, None, 30, 40]],
    'indexes': [[1, 2, 3, 4]],
    'tmp_values': [[40, 30, 10, 10]]
}
df = pd.DataFrame(data)

2. Define the Replacement Function

Create a function that takes a row, makes a copy of flat_values (to avoid modifying the original data), then replaces elements at positions specified by indexes with corresponding values from tmp_values:

def build_new_values(row):
    # Copy the original list to prevent in-place modifications
    updated_list = row['flat_values'].copy()
    # Iterate over index-value pairs and apply replacements
    for idx, val in zip(row['indexes'], row['tmp_values']):
        updated_list[idx] = val
    return updated_list

3. Apply the Function to Generate new_values

Use apply() with axis=1 to run the function on each row and assign the result to your new column:

df['new_values'] = df.apply(build_new_values, axis=1)

4. Verify the Result

You'll now see the desired output in the new_values column:

print(df['new_values'].iloc[0])
# Output: [20, 40, 30, 10, 10, 30, 40]

Key Notes

  • We use .copy() to avoid altering the original flat_values list (since lists are mutable, direct assignment would modify the source data).
  • This solution assumes indexes and tmp_values have matching lengths for every row (as in your example). If mismatched lengths are possible, add a check like assert len(row['indexes']) == len(row['tmp_values']) to catch errors early.

内容的提问来源于stack exchange,提问作者FranG91

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:58:16