-2

How can I copy one column header over to another column header in the same DataFrame. And add a suffix to the second heading in python.
In my data, my header is the month that changes every month. I want to auto-copy that month to the other columns. Thank you

  • 1
    kindly add reproducible example data, wth expected output – sammywemmy Sep 02 '21 at 21:13
  • 1
    Please include a _small_ subset of your data as a __copyable__ piece of code that can be used for testing as well as your expected output for the __provided__ data. See [MRE - Minimal, Reproducible, Example](https://stackoverflow.com/help/minimal-reproducible-example), and [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888) for more information. – Henry Ecker Sep 02 '21 at 21:14
  • Here is a method to do so. https://www.delftstack.com/howto/python-pandas/pandas-create-column-based-on-other-columns/ – Ajay Rathore Sep 02 '21 at 21:16
  • 1
    Read this https://stackoverflow.com/questions/56080859/pandas-copy-column-names-from-one-dataframe-to-another – 0Knowledge Sep 02 '21 at 21:17

2 Answers2

1

df.head()

   total  speeding  alcohol
0   18.8     7.332    5.640
1   18.1     7.421    4.525
2   18.6     6.510    5.208
3   22.4     4.032    5.824
4   12.0     4.200    3.360

Adding new field:

df["total_copy"] = df["total"]

   total  speeding  alcohol  total_copy
0   18.8     7.332    5.640        18.8
1   18.1     7.421    4.525        18.1
2   18.6     6.510    5.208        18.6
3   22.4     4.032    5.824        22.4
4   12.0     4.200    3.360        12.0
MertG
  • 676
  • 1
  • 5
  • 19
0

This is a code sample from https://www.delftstack.com/howto/python-pandas/pandas-create-column-based-on-other-columns/

 import pandas as pd

items_df = pd.DataFrame({
    'Id': [302, 504, 708, 103, 343, 565],
    'Name': ['Watch', 'Camera', 'Phone', 'Shoes', 'Laptop', 'Bed'],
    'Actual Price': [300, 400, 350, 100, 1000, 400],
    'Discount(%)': [10, 15, 5, 0, 2, 7]
})

print("Initial DataFrame:")
print(items_df, "\n")

items_df['Final Price'] = items_df['Actual Price'] - \
    ((items_df['Discount(%)']/100) * items_df['Actual Price'])


print("DataFrame after addition of new column")
print(items_df, "\n")

You can apply the same principle for your column

Ajay Rathore
  • 124
  • 1
  • 7
  • Thank you for the reply. In this example, you are defining the column header (Final Price), not copying another column header. In my data, my header is the month that changes every month. I want to auto-copy that month to the other column. – irfanraorao Sep 02 '21 at 21:34
  • @irfanraorao can you share an example. I am not clear on what is the problem. – Ajay Rathore Sep 03 '21 at 07:19