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

如何在Pandas中将数组格式化为指定的DataFrame格式?

Solution Using Pandas

Got it, let's solve this with Pandas exactly as you need. Here's a straightforward approach that gets you the exact DataFrame format you're after:

Step 1: Prepare your data (example)

First, let's define your input dictionary (adjust this to match your actual data):

import pandas as pd
import numpy as np

# Your original dictionary with numpy arrays
data = {
    'loc.1': np.array([1,2,3,4,7,5,6]),
    'loc.2': np.array([3,4,3,7,7,8,6]),
    'loc.3': np.array([1,4,3,1,7,8,6])
}

Step 2: Convert to the desired DataFrame format

Run these lines to transform your data into the two-column structure you need:

# Convert the dictionary to a Series (keys become index, arrays become values)
series_data = pd.Series(data)

# Convert Series to DataFrame, rename columns, and format the array values
result_df = (
    series_data.reset_index(name='Col2')
    .rename(columns={'index': 'Col1'})
    .assign(Col2=lambda x: x['Col2'].apply(lambda arr: ','.join(map(str, arr))))
)

Step 3: Check the output

If you print result_df, you'll get exactly the format you're looking for:

Col1               Col2
0  loc.1  1,2,3,4,7,5,6
1  loc.2  3,4,3,7,7,8,6
2  loc.3  1,4,3,1,7,8,6

How this works:

  • pd.Series(data) takes your dictionary and turns it into a Series where the keys (loc.1, loc.2...) are the index, and the numpy arrays are the values.
  • reset_index() converts the index into a regular column, and we name the array column Col2 right away. We then rename the index column to Col1 with .rename().
  • The .assign() step uses apply() to convert each numpy array into a comma-separated string: we map each element in the array to a string, then join them with commas.

This approach is efficient and keeps everything within Pandas, making it easy to merge/concatenate with your other table later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:24:10