2

I want to add a constant value as prefix in each elements of list. I want to do something similar to this post . But above answers are using for loop. I want to aviod for loops in my program.

My objective is I have to create a list it values should be "unknown contact number 0", "unknown contact number 1","unknown contact number 2"..."unknown contact number n". here unknown contact number is my prefix. I want to add this element in my list.

So far I tried this,

x=pd.DataFrame(index=range(val))
print ('unknown contact number '+x.index.astype(str)).values.tolist()

My question is Am I adding more complex to my code to avoid for loops? or any other better approaches to solve this problem?

Thanks in advance.

Mohamed Thasin ah
  • 10,754
  • 11
  • 52
  • 111

2 Answers2

5

If performance is important is possible use f-strings, because text function in pandas are slow:

a = [f'unknown contact number {i}' for i in range(N)]

Timings:

N = 10000

In [31]: %timeit ('unknown contact number ' + pd.Series(np.arange(N)).astype(str)).tolist()
6.63 ms ± 708 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [32]: %timeit [f'unknown contact number {i}' for i in range(N)]
317 µs ± 3.61 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks for the solution. I understood this problem in the view of performance, for my learning can you suggest me any other better way in pandas ? +1 – Mohamed Thasin ah Sep 19 '18 at 07:06
  • 1
    @MohamedThasinah - Then use `pd.Series(np.arange(N)).astype(str).radd('unknown contact number ').tolist()`, where is used function [`radd`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.radd.html) - add string from right side ;) – jezrael Sep 19 '18 at 07:10
0

You could try using map with a lambda function if you want to avoid for loops at any cost.

list_ = map(lambda x : 'unknown contact number' + x, df.index.astype(str).values.tolist())

If you're using python 3, then map has an advantage of being lazy. Although using map with lambda function will be a bit slower than list comprehension, but if you have a custom function, you can always use it with map.