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

如何用指定Numpy数组创建仅含2列的Pandas DataFrame?

Got it, let's break down your two questions step by step with concrete, runnable code examples:

1. 创建包含2列的DataFrame,其中一列是含100个元素的序列

First, we'll generate the 100-element sequence, pair it with another column of matching length, then wrap them into a DataFrame. Here's how:

import pandas as pd
import numpy as np

# 生成含100个元素的序列(这里用0到99的整数,你也可以换成其他序列比如随机数)
sequence_col = pd.Series(range(100))
# 准备第二列数据(比如100个随机浮点数,长度和第一列一致)
second_col = np.random.rand(100)

# 用字典构造DataFrame,键是列名,值是对应的数据列
df = pd.DataFrame({'sequence': sequence_col, 'random_values': second_col})

# 打印前5行验证结果
print(df.head())
2. 用indices和test_data创建仅含2列的Pandas DataFrame

Since indices (shape (530,)) and test_data (shape (530,100)) have the same number of rows (530), we can align them row-wise. I'll show you two common approaches based on different needs:

方式1:将test_data的每行作为第二列的单个元素

If you want to store each entire row of test_data as a single entry in the second column:

import pandas as pd
import numpy as np

# 先构造题目中的两个数组(模拟你的输入)
indices = np.array([i for i in range(530)])
test_data = np.random.rand(530, 100)

# 创建DataFrame:第一列是indices,第二列是test_data的每行(转成列表方便存储)
df = pd.DataFrame({
    'indices': indices,
    'test_row_data': list(test_data)
})

# 查看前3行确认结构
print(df.head(3))

方式2:从test_data中选取一列作为第二列

If your actual need is to pair indices with one specific column from test_data (instead of the whole row), you can index into test_data to extract that column:

# 比如选取test_data的第0列作为第二列
df = pd.DataFrame({
    'indices': indices,
    'selected_test_col': test_data[:, 0]  # 用[:, 0]取所有行的第0列
})

print(df.head())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:52:39