Home > Net >  Create a column in dataframe with name of an existing array (initial 4 letters of array name)
Create a column in dataframe with name of an existing array (initial 4 letters of array name)

Time:06-25

I would like to create a column in dataframe having name of an array. For example, the name of array is "customer" then name of the column should be "cust_prop" (initial 4 letters from array's name). Is there any way to get it?

CodePudding user response:

Your question is a bit unclear, but presuming that you are asking: how do i turn the string "customer" into "cust_prop", thats easy enough:

Str = "customer"
NewStr = Str[0:4]   "_prop"

you might need to some extra checking for shorter strings, but i dont know what the behaviour there would be that you want.

If you mean something else, please post some code examples of what you have tried.

CodePudding user response:

You didn't really describe from where you get an array name, so I'll just assume you have it in a variable:

array_name = 'customer'

to slice only first four digit and use it:

new_col_name = f'{array_name[0:4]}_prop'
df[new_col_name] = 1

here I "created" a new column in existing dataframe df, and put value of 1 to the entire column. Instead, you can create a series with any value you want:

series = pd.Series(name=new_col_name, data=array_customer)

Here I created a series with the name as desired, and assumed you have an array_customer variable which holds the array

  • Related