python - 将数据框 reshape 为具有无限行并在没有值的情况下填充零的数据框

标签 python pandas numpy dataframe reshape

有没有办法将 DataFrame reshape 为另一个具有不受限制的行。我只想要一个有 3 列的 DataFrame,不管 DataFrame 中有多少行?

例如,

letters = pd.DataFrame({'Letters' : ['A', 'B', 'C','D', 'E', 'F', 'G', 'H', 
'I','J']})

Letters
0   A
1   B
2   C
3   D
4   E
5   F
6   G
7   H
8   I
9   J

我想像这样用填充零 reshape 它,在没有值(value)的地方。

first   second  third
A       B       C
D       E       F
G       H       I
J       0       0

据我所知,在 numpy reshape 方法中你需要明确地确定你想要多少列和行..

最佳答案

你可以使用 NumPy reshape . arr.reshape((-1, 3)) 告诉 NumPy 将 arr reshape 为 (n, 3) ,其中 n 是根据 arr 的大小和其他给定维度的大小(例如,在本例中,值为 3)计算的。

import numpy as np
import pandas as pd

letters = pd.DataFrame({'Letters' : ['A', 'B', 'C','D', 'E', 'F', 'G', 'H', 'I','J']})
arr = np.empty(((len(letters) - 1)//3 + 1)*3, dtype='O')
arr[:len(letters)] = letters['Letters']
result = pd.DataFrame(arr.reshape((-1, 3)), columns='first second third'.split())
result = result.fillna(0)
print(result)

打印

  first second third
0     A      B     C
1     D      E     F
2     G      H     I
3     J      0     0

关于python - 将数据框 reshape 为具有无限行并在没有值的情况下填充零的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629989/

相关文章:

c# - 我如何在 python 中反序列化 C# datetime?

python - Featuretools 分类处理

python - Pandas 条件创建多列

python - 如何按行对多个条件的 Pandas 数据框列进行求和

python - 使用 numba jit,Python 的段间距离

python - 类型错误 : no salt specified in flask(about sha256)

python - 用同义词替换单词

python - 根据另一个数据帧的 lower_bound 和 upper_bound 删除每列的离群值

python - 导入错误:无法为 sklearn 导入名称 'tree'

python - 如何排序 unsort : array(1). array(2) -> array(3).unsort (reversed array(1).sort