Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何有条件地创建新列?_Python_Pandas - Fatal编程技术网

Python 如何有条件地创建新列?

Python 如何有条件地创建新列?,python,pandas,Python,Pandas,我想在我的数据框中添加一个名为id的新列。如果id的值只是一个固定的数字,那么我可以创建一个新列,如下所示: id_value = 1 df.insert(0, 'id', id_value) id 1 1 1 2 2 2 3 3 3 ... 但是,在本例中,我需要创建3行的批,如下所示: id_value = 1 df.insert(0, 'id', id_value) id 1 1 1 2 2 2 3 3 3 ... 我该怎么做呢?您可以通过np.arange创建数组,整数除以3,因

我想在我的数据框中添加一个名为
id
的新列。如果
id
的值只是一个固定的数字,那么我可以创建一个新列,如下所示:

id_value = 1
df.insert(0, 'id', id_value)
id
1
1
1
2
2
2
3
3
3
...
但是,在本例中,我需要创建3行的批,如下所示:

id_value = 1
df.insert(0, 'id', id_value)
id
1
1
1
2
2
2
3
3
3
...

我该怎么做呢?

您可以通过
np.arange
创建数组,整数除以
3
,因此从
0
开始,如果需要自定义第一个数字添加
id\u值

id_value = 1
df.insert(0, 'id', np.arange(len(df)) // 3 + id_value)
如果有默认索引值也起作用:

df = pd.DataFrame({'a':np.random.randint(10, size=10)})

id_value = 1
df.insert(0, 'id', df.index // 3 + id_value)
print (df)
   id  a
0   1  2
1   1  8
2   1  5
3   2  3
4   2  1
5   2  1
6   3  9
7   3  2
8   3  7
9   4  5

我想我不明白。成批的行与插入列有什么关系?这有什么“条件”呢?@KarlKnechtel:请看答案。