在 Python 中将带有空格的字符串转换为具有所需尺寸的数据框

Convert a string with whitespaces to a dataframe with desired dimensions in Python

在 Python 中将带有空格的字符串转换为具有所需尺寸(X 列和 Y 行)的某些数据框(一些 'table')的聪明方法是什么?

假设我的字符串是 string = 'A B C D E F G H I J K L',我想将它转换成一个 3 列 x 4 行的数据框。

我想有一些有用的 pandas/numpy 工具。

使用Numpy.reshape()

import numpy as np
import pandas as pd

string = 'A B C D E F G H I J K L'

list1 = [char for char in string.split(' ') if char != '']
df = pd.DataFrame(np.reshape(list1,[3,4]))

输出:

   0  1  2  3
0  A  B  C  D
1  E  F  G  H
2  I  J  K  L

糟糕...这是 3 列 x 4 行:

pd.DataFrame(np.reshape(list1,[4,3]))

   0  1  2
0  A  B  C
1  D  E  F
2  G  H  I
3  J  K  L

编辑:将导入放在首位。