I have a dataframe and I want to change the columns of that with a specifc way. I want to change the 0-27 of the columns to d0, d1, d2, …d27. And the 28-56 to d10-d127, and the third 28 of the columns (56-84) to (d20-d227) and etc. Can you please help me with that.
I already did that with another dataframe to rename the columns of df with 7 step. Here is the code I used for that. But, this does not work for the new case.
df = dataframe with size (10*71. The first column is id)
b = df.shape[1]-1
df.columns = np.hstack(['id', np.core.defchararray.add('d', (b%7+b//7*10).astype(str))])
The new case is:
df= dataframe with size (10*281. The first column is id)
import numpy as np
import pandas as pd
A = np.random.randint(10, size = (10, 281))
A_df = pd.DataFrame(A)
Can you please help me with that? Thank you so much
>Solution :
You should use integer division and modulo operations to get the new column names.
import numpy as np
import pandas as pd
A = np.random.randint(10, size=(10, 281))
A_df = pd.DataFrame(A)
b = A_df.shape[1] - 1
col_indices = np.arange(b) // 28 * 10 + np.arange(b) % 28
new_col_names = np.hstack(['id', np.core.defchararray.add('d', col_indices.astype(str))])
A_df.columns = new_col_names
print(A_df)