Reputation: 8247
I have following data frame in Pandas
Date stockA stockB stockC stockD stockE
2020-01-01 1 1 2 1 3
2020-01-01 1 2 2 1 2
2020-01-01 1 1 3 2 1
2020-01-01 3 1 2 1 2
I want to add prefix for each column e.g. for stockA:01, stockB:02 so on and so forth.
My desired data frame would be
Date stockA stockB stockC stockD stockE
2020-01-01 011 021 032 041 053
2020-01-01 011 022 032 041 052
2020-01-01 011 021 033 042 051
2020-01-01 013 021 032 041 052
I have 25 columns likewise. How can I do it in pandas?
Upvotes: 1
Views: 1156
Reputation: 30930
Use:
m = df.columns.str.contains('stock')
cols_change = df.columns[m]
num = ('0'+pd.Index(range(1,len(cols_change)+1)).astype(str)).str[-2:]
df.columns = df.columns[~m].tolist()+[f'{name}:{n}' for n,name in zip(num,cols_change)]
print(df)
Date stockA:01 stockB:02 stockC:03 stockD:04 stockE:05
0 2020-01-01 1 1 2 1 3
1 2020-01-01 1 2 2 1 2
2 2020-01-01 1 1 3 2 1
3 2020-01-01 3 1 2 1 2
or with pd.Index.difference
cols_change = df.columns.difference(['Date'])
num = ('0'+pd.Index(range(1,len(cols_change)+1)).astype(str)).str[-2:]
df.columns = ['Date']+[f'{name}:{n}' for n,name in zip(num,cols_change)]
Upvotes: 1
Reputation: 2564
A somewhat more cumbersome but perhaps more readable solution:
v = [1,23,33]
cols = {'A': v, 'B': v, 'C': v, 'D': v, 'E': v,
'F': v, 'G': v, 'H': v, 'I': v, 'J': v}
df = pd.DataFrame(data = cols,
index = ['2020-01-01']*3,
columns = cols)
for n, col in enumerate(df.columns, 1):
df[col] = str(n).zfill(2) + df[col].astype(str)
>>
A B C D E F G H I J
2020-01-01 011 021 031 041 051 061 071 081 091 101
2020-01-01 0123 0223 0323 0423 0523 0623 0723 0823 0923 1023
2020-01-01 0133 0233 0333 0433 0533 0633 0733 0833 0933 1033
Upvotes: 2
Reputation: 75120
Try with df.radd
:
m = df.set_index('Date')
#add prefix 0X if less than 10 else add prefix X
m = m.astype(str).radd([f"0{i}" if i<10 else f"{i}"
for i in range(1,m.shape[1]+1)]).reset_index()
print(m)
Date stockA stockB stockC stockD stockE
0 2020-01-01 011 021 032 041 053
1 2020-01-01 011 022 032 041 052
2 2020-01-01 011 021 033 042 051
3 2020-01-01 013 021 032 041 052
Upvotes: 5