将numpy的ndarray从1维变为多维数组在Python中。

huangapple go评论88阅读模式
英文:

Change numpy ndarray shape from 1d to multidimensi in python

问题

| df |
| --- |
| \[0,1,2\] |
| \[3,4,5\] |

我想将它变成这样的表格:

| df1 | df2 | df3 |
| --- | --- | --- |
| \[0\] | \[1\] | \[2\] |
| \[3\] | \[4\] | \[5\] |

我尝试过仅针对一个数据,但在尝试对df中的所有数据进行操作时多次失败。

这是我针对一个数据的代码:

```python
df1, df2, df3 = np.split(df.iloc[0], 3)

结果是:df1 = array([0], dtype=float32),这是正确的,但没有涵盖所有的数据。


<details>
<summary>英文:</summary>

| df |
| --- |
| \[0,1,2\] |
| \[3,4,5\] |

and i want to make it as this table

| df1 | df2 | df3 |
| --- | --- | --- |
| \[0\] | \[1\] | \[2\] |
| \[3\] | \[4\] | \[5\] |

i have tried just for one data and failed several times while i tried for all data in df

this my code for one data

    df1,df2,df3 = np.split(df.iloc\[0\].3) the result was df1 = array(\[0\], dtype=float32)

it was right but didnt cover all the data


</details>


# 答案1
**得分**: 1

如果您的列表中的项目数量是固定的,例如根据您上面的示例为3个,您可以使用以下代码:

```python
df[['df1', 'df2', 'df3']] = pd.DataFrame(df.df.tolist(), index=df.index)

然后删除原始列:

df.drop(columns=['df'], inplace=True)
   df1  df2  df3
0    0    1    2
1    3    4    5
英文:

If your number of items in the list is fixed, i.e. 3 as per your example above, you can use:

df[[&#39;df1&#39;,&#39;df2&#39;, &#39;df3&#39;]] = pd.DataFrame(df.df.tolist(), index= df.index)

Then drop the original column:

df.drop(columns=[&#39;df&#39;], inplace = True)


   df1  df2  df3
0    0    1    2
1    3    4    5

答案2

得分: 0

你可以通过Pandas(Python数据分析库)来实现这个,以下是代码:

import pandas as pd
data = [[0, 1, 2], [3, 4, 5]]
df = pd.DataFrame(data)
df.columns = [f"df{i+1}" for i in range(len(df.columns))]
print(df)
英文:

You can do this via Pandas (Python Data Analysis Library), here is the code below:

import pandas as pd
data = [[0, 1, 2], [3, 4, 5]]
df = pd.DataFrame(data)
df.columns = [f&quot;df{i+1}&quot; for i in range(len(df.columns))]
print(df)

huangapple
  • 本文由 发表于 2023年7月24日 14:55:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76752047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定