简体   繁体   中英

Concatenate index and string to new column

I have a dataframe of 3 columns(including index):

   name   age
 0 satya   24
 1 abc     26
 2 xyz     29
 3 def     32

so need to add one new column detail which will store the detail file name and the value in that column should be like (str(file_index no))

   name   age  detail
 0 satya   24  file_0
 1 abc     26  file_1
 2 xyz     29  file_2 
 3 def     32  file_3

to achieve that I tried the following

df['detail']= str('file_'+df.index)   #not working shows error
df['detail'] = str('file'+'_'+str(df.index))  #worked but not what i want
df['detail'] = str(s+'_'+df.index[0].astype(str))  #error

implemented for loop and iterrows

 for index, row in df.iterrows():
        df['detail'] = str('file'+'_'+row[index])   #IndexError: index out of bounds

for index, row in df.iterrows():
df['idx'] = str(s+'_'+df.index[row].astype(str))  ###IndexError: arrays used as indices must be of integer (or boolean) type

So please suggest.

You can use astype with index :

df['detail']= 'file_' + df.index.astype(str)
print df
    name  age  detail
0  satya   24  file_0
1    abc   26  file_1
2    xyz   29  file_2
3    def   32  file_3

Next solution is use map :

df['detail'] = 'file_' + df.index.map(str)

#python 3.6+ solution
df['detail'] = [f"file_{i}" for i in df.index]

Comparing:

#[40000 rows x 2 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [153]: %timeit df['detail']= 'file_' + df.index.astype(str)
31.2 ms ± 423 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [154]: %timeit df['detail1'] = 'file_' + df.index.map(str)
16.9 ms ± 411 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [155]: %timeit df['detail'] = [f"file_{i}" for i in df.index]
2.95 ms ± 180 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM