afshin
afshin

Reputation: 1833

create column by combining index #, string

I have a dataframe containing a column of strings. I want to create a new column that combines the index number and the string column together in a list comprehension. The following code does this operation iterating in a loop:

df=pd.DataFrame({'strings': ['string1','string2','string3']})
new_col=[]
for i in df['strings'].index.values:
    new_col.append(str(i)+','+df['strings'][i])
df['new_col']=new_col

Above code works but is slow. How can I do this in a list comprehension?

Upvotes: 1

Views: 1360

Answers (4)

Jeff R
Jeff R

Reputation: 90

This will provide a new column with the index plus your string column

df['new'] = df.index.astype(str) + df['strings']

Upvotes: 0

Sudharsana Rajasekaran
Sudharsana Rajasekaran

Reputation: 328

Reset Index and then by using the column to create the new column

df=df.reset_index()
df['new_col']=df['index'].astype(str)+','+df['strings']

Upvotes: 0

Celius Stingher
Celius Stingher

Reputation: 18367

If you want list comprehensions then I would recommend using zip()

import pandas as pd
df=pd.DataFrame({'strings': ['string1','string2','string3']})
df['new_col'] = [str(y)+','+str(x) for x,y in zip(df['strings'],df.index.values.astype(int))]
print(df)

Output:

   strings    new_col
0  string1  0,string1
1  string2  1,string2
2  string3  2,string3

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150755

You can convert the index to string and add as usual (arrays of) strings:

df['new_col'] = df['strings'].index.astype(str) + ',' + df['strings']

Output:

   strings    new_col
0  string1  0,string1
1  string2  1,string2
2  string3  2,string3

Upvotes: 2

Related Questions