英文:
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[['df1','df2', 'df3']] = pd.DataFrame(df.df.tolist(), index= df.index)
Then drop the original column:
df.drop(columns=['df'], 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"df{i+1}" for i in range(len(df.columns))]
print(df)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论