简体   繁体   中英

Get the name of a column and create data from it in dataframe pandas

I am currently trying to generate new columns [Y, Z] based on the name of another column [X] of the same Dataframe. The problem is that I have not been able to obtain the name of the column and pass it as data to a new column.

I am trying something like this:

df['Y'] = df.assign(lambda c: df.columns.values['X'])
df['Z'] = df.apply(lambda c: df.columns.values['X'])

As an example, the dataframe would look something like this:

>>> df_original
       name  example_col
  0  shakir   33
  1   rafiq   37
  2     dev   36
  3   suraj   30

>>> df_new
       name  new_col        value
  0  shakir   example_col    33
  1   rafiq   example_col    37
  2     dev   example_col    36
  3   suraj   example_col    30

But I am not very close to a solution and I've already tried in various ways... :(

Please give me an idea where should I go?

Thank you in advance for your time, I will be attentive to your answers!

Regards!

Assuming you know the index of the column you want to copy the name of then:

df_new = df_original.copy()
df_new.loc[:, 'new_col'] = df_new.columns[1]

Updated answer as per the edited post:

Example:

>>> df
     name  example_col
0  shakir           33
1   rafiq           37
2     dev           36
3   suraj           30

Solution:

you can try using set_index() with stack and the rename the new default formed columns level_1 & 0 as follows:

>>> df.set_index('name').stack().reset_index().rename(columns={'level_1': 'new_col', 0:'value'})
     name      new_col  value
0  shakir  example_col     33
1   rafiq  example_col     37
2     dev  example_col     36
3   suraj  example_col     30

OR - you can try with pd.melt :

>>> pd.melt(df, id_vars=['name'], var_name='new_col')
     name      new_col  value
0  shakir  example_col     33
1   rafiq  example_col     37
2     dev  example_col     36
3   suraj  example_col     30

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