如何在 Python 中创建全零数据框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28356492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to create all zero dataframe in Python
提问by lserlohn
I want to create a dataframe in Python with 24 columns (indicating 24 hours), which looks like this:
我想在 Python 中创建一个包含 24 列(表示 24 小时)的数据框,如下所示:
column name 0 1 2 3 ... 24
row 1 0 0 0 0 0
row 2 0 0 0 0 0
row 3 0 0 0 0 0
I would like to know how to initialize it? and in the future, I may add row 4, with all "0", how to do that? Thanks,
我想知道如何初始化?将来,我可能会添加第 4 行,全部为“0”,该怎么做?谢谢,
采纳答案by user2589273
You can create an empty numpy array, convert it to a dataframe, and then add the header names.
您可以创建一个空的 numpy 数组,将其转换为数据帧,然后添加标题名称。
import numpy
a = numpy.zeros(shape=(3,24))
df = pd.DataFrame(a,columns=['col1','col2', etc..])
to set row names use
设置行名称使用
df.set_index(['row1', 'row2', etc..])
if you must.
如果你必须。
回答by Andy Hayden
There's a trick here: when DataFrame (or Series) constructor is passed a scalar as the first argument this value is propogated:
这里有一个技巧:当 DataFrame(或系列)构造函数被传递一个标量作为第一个参数时,这个值被传播:
In [11]: pd.DataFrame(0, index=np.arange(1, 4), columns=np.arange(24))
Out[11]:
0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 21 22 23
1 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
2 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0 0 0 0 ... 0 0 0 0 0 0 0 0 0 0
[3 rows x 24 columns]
Note: np.arange
is numpy's answer to python's range.
注意:np.arange
是 numpy 对 python 范围的回答。