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

基于行列坐标填充DataFrame空单元格的技术咨询

Solution to Fill Empty Cells with Coordinate Lists in DataFrame

Got it, let's tackle this problem step by step. First, let's replicate your initial DataFrame in pandas (we'll use NaN to represent the empty cell):

import pandas as pd
import numpy as np

# Original DataFrame with empty cell
df_initial = pd.DataFrame({
    'col1': [np.nan, 4],
    'col2': [4, 3],
    'col3': [3, 2],
    'col4': [2, 1],
    'col5': [1, 0]
})

Step-by-Step Implementation

The core idea is to generate new rows based on the values from the first row, then append your original second row at the end. Here's how to do it:

  1. Extract reference values: Grab the values from col2 to col5 of the first row (4, 3, 2, 1) — these will be the values for col5 in our new top 4 rows.
  2. Build coordinate rows: For each value x in that list, create a row where the first four columns are [4, x], [3, x], [2, x], [1, x] respectively.
  3. Combine everything: Merge the new rows with your original second row to get the final result.
# Extract values from first row (col2-col5) to use as col5 in new rows
reference_values = df_initial.iloc[0, 1:].tolist()  # Output: [4, 3, 2, 1]

# Generate new rows with coordinate lists
new_rows = []
for x in reference_values:
    new_row = {
        'col1': [4, x],
        'col2': [3, x],
        'col3': [2, x],
        'col4': [1, x],
        'col5': x
    }
    new_rows.append(new_row)

# Convert new rows to DataFrame
df_new = pd.DataFrame(new_rows)

# Append the original second row to complete the final DataFrame
df_final = pd.concat([df_new, df_initial.iloc[1:]], ignore_index=True)

# Print the result
print(df_final)

Expected Output

Running the code above will produce exactly the DataFrame you want:

col1     col2     col3     col4  col5
0  [4, 4]  [3, 4]  [2, 4]  [1, 4]     4
1  [4, 3]  [3, 3]  [2, 3]  [1, 3]     3
2  [4, 2]  [3, 2]  [2, 2]  [1, 2]     2
3  [4, 1]  [3, 1]  [2, 1]  [1, 1]     1
4       4        3        2        1     0

Quick Notes

  • If your original empty cell uses an empty string instead of NaN, just adjust the initial DataFrame creation — the core logic stays the same.
  • Using ignore_index=True in pd.concat ensures the final DataFrame has a continuous index instead of retaining the original indices from the two parts.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 21:27:40