Home > other >  Change the structure of column name
Change the structure of column name

Time:02-26

I have the column as

id_no| 2021-05-19 00:00:00 | 2021-05-20 00:00:00 | decider
 100       20                      20              878
 200       64                      38              917

here idno is the index and the rest are columns I want the outupt as

id_no| 2021-05-19 | 2021-05-20 | decider
 100       20          20          878
 200       64          38          917

I tried converting the column names but just column name is not getting changed and column names are in datetime format except the population column. I tried below code

for (columnName, columnData) in df.iteritems():
       columnName = pd.to_datetime(columnName)

CodePudding user response:

We can try str slice when other column length are not greater than 10

df.columns = df.columns.astype(str).str[:10]
df
Out[356]: 
   id_no  2021-05-19  2021-05-20  decider
0    100          20          20      878
1    200          64          38      917

CodePudding user response:

Changing a loop variable changes only... the loop variable, not the column name! You must create a list of strings representing the new column names, and make it the new column index:

new_columns = [df.columns[0]]   \
              pd.to_datetime(df.columns[1:-1]).astype(str).tolist()  \
              [df.columns[-1]]
df.columns = new_columns

CodePudding user response:

You can just assign a list of names to the columns attribute of your df.

data = {'id_no': {0: 100, 1: 200},
 '2021-05-19 00:00:00': {0: 20, 1: 64},
 '2021-05-20 00:00:00': {0: 20, 1: 38},
 'decider': {0: 878, 1: 917}}

df = pd.DataFrame(data)

df.columns = ['id_no', '2021-05-19', '2021-05-20', 'decider'] # simple solution
# edit, you can use a list comprehension with conditional
df.columns = [str(x)[0:10] if x[0] == '2' else x for x in df.columns]

Output:

    id_no   2021-05-19  2021-05-20  decider
0   100     20          20          878
1   200     64          38          917
  • Related