在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 originalflat_valueslist (since lists are mutable, direct assignment would modify the source data). - This solution assumes
indexesandtmp_valueshave matching lengths for every row (as in your example). If mismatched lengths are possible, add a check likeassert len(row['indexes']) == len(row['tmp_values'])to catch errors early.
内容的提问来源于stack exchange,提问作者FranG91
相关产品推荐
相关产品推荐

