This is my DataFrame:
import pandas as pd
df = pd.DataFrame(
{
'a': [4, 3, 2, 2, 6]
}
)
And this is the expected output: I want to create column id:
a id
0 4 x_0
1 3 x_1
2 2 x_2
3 2 x_3
4 6 x_4
I can create id like this but I think there is a one-liner for this:
df['id'] = np.arange(len(df))
df['id'] = 'x_' + df.id.astype(str)
I prefer a solution that does not use index.
>Solution :
If you want a one-liner, you have to convert your array to Series (raw arrays are not practical for string concatenation):
df['id'] = 'x_' + pd.Series(np.arange(len(df)), dtype=str)
# or
df['id'] = pd.Series(np.arange(len(df)), dtype=str).radd('x_')
Output:
a id
0 4 x_0
1 3 x_1
2 2 x_2
3 2 x_3
4 6 x_4