创建一个零填充的熊猫数据框

创建给定大小的零填充熊猫数据框的最佳方法是什么?

我用过:

zero_data = np.zeros(shape=(len(data),len(feature_list)))
d = pd.DataFrame(zero_data, columns=feature_list)

有更好的方法吗?

niedakh asked 2019-10-08T11:47:41Z
6个解决方案
86 votes

你可以试试这个:

d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)
Shravan answered 2019-10-08T11:47:47Z
17 votes

我认为最好用numpy做到这一点

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))
AlexG answered 2019-10-08T11:48:11Z
7 votes

类似于@Shravan,但不使用numpy:

  height = 10
  width = 20
  df_0 = pd.DataFrame(0, index=range(height), columns=range(width))

然后,您可以使用它做任何您想做的事情:

post_instantiation_fcn = lambda x: str(x)
df_ready_for_whatever = df_0.applymap(post_instantiation_fcn)
WaveRider answered 2019-10-08T11:48:41Z
2 votes

如果您希望新数据框具有与现有数据框相同的索引和列,则可以将现有数据框乘以零:

df_zeros = df * 0
chakuRak answered 2019-10-08T11:49:07Z
1 votes

如果您已经有一个数据框,这是最快的方法:

In [1]: columns = ["col{}".format(i) for i in range(10)]
In [2]: orig_df = pd.DataFrame(np.ones((10, 10)), columns=columns)
In [3]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
10000 loops, best of 3: 60.2 µs per loop

相比于:

In [4]: %timeit d = pd.DataFrame(0, index = np.arange(10), columns=columns)
10000 loops, best of 3: 110 µs per loop

In [5]: temp = np.zeros((10, 10))
In [6]: %timeit d = pd.DataFrame(temp, columns=columns)
10000 loops, best of 3: 95.7 µs per loop
mtd answered 2019-10-08T11:49:39Z
1 votes

假设有一个模板DataFrame,要在此处填充零值进行复制...

如果您的数据集中没有NaN,则乘以零可能会更快:

In [19]: columns = ["col{}".format(i) for i in xrange(3000)]                                                                                       

In [20]: indices = xrange(2000)

In [21]: orig_df = pd.DataFrame(42.0, index=indices, columns=columns)

In [22]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
100 loops, best of 3: 12.6 ms per loop

In [23]: %timeit d = orig_df * 0.0
100 loops, best of 3: 7.17 ms per loop

改进取决于DataFrame的大小,但从未发现它会变慢。

只是为了它:

In [24]: %timeit d = orig_df * 0.0 + 1.0
100 loops, best of 3: 13.6 ms per loop

In [25]: %timeit d = pd.eval('orig_df * 0.0 + 1.0')
100 loops, best of 3: 8.36 ms per loop

但:

In [24]: %timeit d = orig_df.copy()
10 loops, best of 3: 24 ms per loop

编辑!!!

假设您有一个使用float64的框架,那么这将是最快的! 通过将0.0替换为所需的填充编号,它还可以生成任何值。

In [23]: %timeit d = pd.eval('orig_df > 1.7976931348623157e+308 + 0.0')
100 loops, best of 3: 3.68 ms per loop

根据口味的不同,可以从外部定义nan,并做出通用的解决方案,而不管特定的浮点类型如何:

In [39]: nan = np.nan
In [40]: %timeit d = pd.eval('orig_df > nan + 0.0')
100 loops, best of 3: 4.39 ms per loop
Mark Horvath answered 2019-10-08T11:50:46Z
translate from https://stackoverflow.com:/questions/22963263/creating-a-zero-filled-pandas-data-frame