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

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

Change numpy ndarray shape from 1d to multidimensi in python

问题

  1. | df |
  2. | --- |
  3. | \[0,1,2\] |
  4. | \[3,4,5\] |
  5. 我想将它变成这样的表格:
  6. | df1 | df2 | df3 |
  7. | --- | --- | --- |
  8. | \[0\] | \[1\] | \[2\] |
  9. | \[3\] | \[4\] | \[5\] |
  10. 我尝试过仅针对一个数据,但在尝试对df中的所有数据进行操作时多次失败。
  11. 这是我针对一个数据的代码:
  12. ```python
  13. df1, df2, df3 = np.split(df.iloc[0], 3)

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

  1. <details>
  2. <summary>英文:</summary>
  3. | df |
  4. | --- |
  5. | \[0,1,2\] |
  6. | \[3,4,5\] |
  7. and i want to make it as this table
  8. | df1 | df2 | df3 |
  9. | --- | --- | --- |
  10. | \[0\] | \[1\] | \[2\] |
  11. | \[3\] | \[4\] | \[5\] |
  12. i have tried just for one data and failed several times while i tried for all data in df
  13. this my code for one data
  14. df1,df2,df3 = np.split(df.iloc\[0\].3) the result was df1 = array(\[0\], dtype=float32)
  15. it was right but didnt cover all the data
  16. </details>
  17. # 答案1
  18. **得分**: 1
  19. 如果您的列表中的项目数量是固定的,例如根据您上面的示例为3个,您可以使用以下代码:
  20. ```python
  21. df[['df1', 'df2', 'df3']] = pd.DataFrame(df.df.tolist(), index=df.index)

然后删除原始列:

  1. df.drop(columns=['df'], inplace=True)
  1. df1 df2 df3
  2. 0 0 1 2
  3. 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:

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

Then drop the original column:

  1. df.drop(columns=[&#39;df&#39;], inplace = True)
  2. df1 df2 df3
  3. 0 0 1 2
  4. 1 3 4 5

答案2

得分: 0

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

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

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

  1. import pandas as pd
  2. data = [[0, 1, 2], [3, 4, 5]]
  3. df = pd.DataFrame(data)
  4. df.columns = [f&quot;df{i+1}&quot; for i in range(len(df.columns))]
  5. 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:

确定