Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.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,我有一个数据帧- DATE CITY_NAME WEEK_NUM 0 2019-12-01 Bangalore 48 1 2019-12-01 Delhi 48 2 2019-12-02 Bangalore 49 3 2019-12-02 Delhi 49 现在我想向dataframe添加一个新列,并在循环中向新列添加一行。是我干的- R1['Hi']=0 for a,b i

我有一个数据帧-

    DATE        CITY_NAME     WEEK_NUM
0   2019-12-01  Bangalore       48
1   2019-12-01  Delhi           48
2   2019-12-02  Bangalore       49
3   2019-12-02  Delhi           49
现在我想向dataframe添加一个新列,并在循环中向新列添加一行。是我干的-

R1['Hi']=0

for a,b in zip(R1['DATE'],R1['CITY_NAME']):
    R1['Hi'].loc[-1]=random.randrange(10)
我在这里使用的是默认值5,但我是 但它的表现-

      DATE       CITY_NAME  WEEK_NUM    Hi
0   2019-12-01  Bangalore   48          0
1   2019-12-01  Delhi       48          0
2   2019-12-02  Bangalore   49          0
3   2019-12-02  Delhi       49          0
假设rand的f输出为[2,3,1,6]

那么最终的输出将是-

           DATE     CITY_NAME    WEEK_NUM       Hi
    0   2019-12-01  Bangalore      48           2
    1   2019-12-01  Delhi          48           3
    2   2019-12-02  Bangalore      49           1
    3   2019-12-02  Delhi          49           6
打印(例如):


编辑:(使用索引)

打印(例如):


编辑2:

df['Hi'] = 0
for i in df.index:
    df.loc[i,['Hi']] = random.randrange(10)
印刷品:

         DATE  CITY_NAME  WEEK_NUM  Hi
0  2019-12-01  Bangalore        48   7
1  2019-12-01      Delhi        48   1
2  2019-12-02  Bangalore        49   2
3  2019-12-02      Delhi        49   8

不知道为什么要使用循环,您可以不使用循环: 如果使用numpy:

R1['Hi'] = np.random.randint(10, size = 4)

我不太明白。想要的输出是什么?@AndrejKeselyi添加了想要的输出。我想用索引和循环得到答案,因为我在一个更大的函数中使用了它。为什么2019-12-01班加罗尔会在HI列中打印呢?@ubuntu\u noob这只是个例子。查看我的更新答案,了解更多信息
         DATE  CITY_NAME  WEEK_NUM                          Hi
0  2019-12-01  Bangalore        48  2019-12-01 - Bangalore - 5
1  2019-12-01      Delhi        48      2019-12-01 - Delhi - 0
2  2019-12-02  Bangalore        49  2019-12-02 - Bangalore - 8
3  2019-12-02      Delhi        49      2019-12-02 - Delhi - 5
df['Hi'] = 0
for i in df.index:
    df.loc[i,['Hi']] = random.randrange(10)
         DATE  CITY_NAME  WEEK_NUM  Hi
0  2019-12-01  Bangalore        48   7
1  2019-12-01      Delhi        48   1
2  2019-12-02  Bangalore        49   2
3  2019-12-02      Delhi        49   8
R1['Hi'] = np.random.randint(10, size = 4)