1

Context:

i am new in Pandas and I need a function that creates new columns based on existing columns. The new columns name will have the name from the original column plus new characters (example: create a "As NEW" column from "As" column). Can i access the old column header string to make the name of the new column?

Problem:

i have df['columnA'] and need to get "columnA" string

2
  • Please provide what you already tried. Commented Oct 22, 2017 at 22:13
  • @scharette i didn't figured out any code, but edited the question to make it easier to understand Commented Oct 22, 2017 at 22:28

3 Answers 3

2

If I understand you correctly, this may be what you're looking for.

You can use str.contains() for the columns, then use string formatting to create the new column name.

df = pd.DataFrame({'col1':['A', 'A', 'B','B'], 'As': ['B','B','C','C'], 'col2': ['C','C','A','A'], 'col3': [30,10,14,91]})
col = df.columns[df.columns.str.contains('As')]
df['%s New' % col[0]] = 'foo'
print (df)
   As   col1 col2  col3 As New
0  B    A    C    30    foo
1  B    A    C    10    foo
2  C    B    A    14    foo
3  C    B    A    91    foo
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that you have an empty DataFrame df with columns, you could access the columns of df as a list with:

 >>> df.columns
Index(['columnA', 'columnB'], dtype='object')

.columns will allow you to overwrite the columns of df, but you don't need to pass in another Index. You can pass it a regular list, like so:

>>> df.columns = ['columna', 'columnb']
>>> df
Empty DataFrame
Columns: [columna, columnb]
Index: []

Comments

0

This can be done through the columns attribute.

cols = df.columns
# Do whatever operation you want on the list of strings in cols
df.columns = cols

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.