ubuntu_noob
ubuntu_noob

Reputation: 2365

Adding rows at a specific column

I have a dataframe-

    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

Now I want to add a new column to the dataframe and add a row to the new column in a loop. I did this-

R1['Hi']=0

for a,b in zip(R1['DATE'],R1['CITY_NAME']):
    R1['Hi'].loc[-1]=random.randrange(10)

I am using a default value 5 here but I am but its showing-

      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

lets assume the f output of rand is [2,3,1,6]

then final output will be-

           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

Upvotes: 1

Views: 47

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195438

import random

df['Hi'] = [random.randrange(10) for _ in range(len(df))]

print(df)

Prints (for example):

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

Edit: (using indices)

df['Hi'] = 0
for i, a, b in zip(df.index, df.DATE, df.CITY_NAME):
    df.loc[i,['Hi']] = '{} - {} - {}'.format(a, b, random.randrange(10))

Prints (for example):

         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

EDIT2:

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

Prints:

         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

Upvotes: 1

chambeeee
chambeeee

Reputation: 95

Not sure why you use a loop, you can do it without that: If you use numpy :

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

Upvotes: 0

Related Questions