Anna
Anna

Reputation: 974

How to stretch value for the lengths of column in pandas?

There is a df

df = 

date        foo   bar
2019-01-01  foo1  bar1
2019-02-01  foo2  bar2
2019-03-01  foo3  bar3

and a variable df_if = '123'

I need to make an additional column df_id with the value of df_if

# My desirable output is:

date        foo   bar   df_id
2019-01-01  foo1  bar1  123
2019-02-01  foo2  bar2  123
2019-03-01  foo3  bar3  123

I tried to do like this

df['df_id'] = df_id * len(df)

But it multiplies also the variable itself

# The result is:

date        foo   bar   df_id
2019-01-01  foo1  bar1  123123123
2019-02-01  foo2  bar2  123123123
2019-03-01  foo3  bar3  123123123

In other script the same technique works properly, I can't get why it multiplies the value

Upvotes: 1

Views: 303

Answers (1)

jezrael
jezrael

Reputation: 863166

Because it is string, so if multiple by scalar it repeat values:

print ('a' * 3)
aaa

print (df_id * 3)
123123123

Maybe you want convert values to one element list:

print (['a'] * 3)
['a', 'a', 'a']

print ([df_id] * 3)
['123', '123', '123']

df['df_id'] = [df_id] * len(df)

But simpliest is:

df['df_id'] = df_id 

Or:

df = df.assign(df_id = df_id)

Upvotes: 2

Related Questions