I wonder how to change the names of columns which name has begin on "Unnamed:". Want to replace those columns with years from 1960 to 2019. Have you guys any idea how?
Asked
Active
Viewed 526 times
0
-
How are you creating your dataframe? Reading from csv? It seems like row number 2 is what you want as your column names? – Tobias Bergkvist Jul 10 '22 at 13:51
-
Welcome to SO. Please don't post images, include the information as text (in code fences). If you're using a Pandas dataframe (please clarify by appropriate tags) use [`.rename()`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html) with a suitable mapper and `axis=1`. – Timus Jul 10 '22 at 13:52
-
Tobias, yes form csv. And yes exactly about row number 2, I wanna to name columns as row 2. – Oskar Jul 10 '22 at 13:55
-
https://stackoverflow.com/a/31328974/14066512 – Rajesh Jul 10 '22 at 14:17
-
You can use the header argument to `pd.read_csv(..., header=1)` to select a specific row to use for the column names. Alternatively, use `pd.read_csv(..., skiprows=1)` to skip the first row of the file. See https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html – Tobias Bergkvist Jul 10 '22 at 14:18
1 Answers
3
You could loop
over the columns and check if it needs to be renamed. This code assumes that they are in order of the year you want them.
year = 1960
for col in my_df.columns:
if col.startswith('Unnamed'):
my_df.rename(columns = {col :f'{year}'}, inplace = True)
year += 1

Damiaan
- 777
- 4
- 11