I have the following df:
TAN.SK SHA.LO
A 0.05 0.01
S 0.04 0.44
D 0.08 -0.18
I would like the new df to be like:
TAN SHA
A 0.05 0.01
S 0.04 0.44
D 0.08 -0.18
Basically remove from the column names .SK
and .LO
This is what I have tried:
df.rename(columns=lambda x: x.split('.')[0])
df.columns=df.split('.')[0]
This second case works perfectly in case of df.index
Unfortunately, the “Error: Can't rename columns that don't exist.” message appears in the RStudio console. The reason for this is that both plyr and dplyr provide a rename function. Because we loaded the dplyr package last, the R programming language tries to use the dplyr package's rename function.
Select a column, and then select Transform > Rename. You can also double-click the column header. Enter the new name.
To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.
To insert, rename, or delete a column, you'll need a Smartsheet license and Owner-level or Admin-level sharing permissions to the sheet. Find out if this capability is included in Smartsheet Regions or Smartsheet Gov.
DataFrame.rename() does NOT change the DataFrame in place (per default), so you have to assign it back:
In [134]: df = df.rename(columns=lambda x: x.split('.')[0])
In [135]: df
Out[135]:
TAN SHA
A 0.05 0.01
S 0.04 0.44
D 0.08 -0.18
or
In [139]: df.rename(columns=lambda x: x.split('.')[0], inplace=True)
In [140]: df
Out[140]:
TAN SHA
A 0.05 0.01
S 0.04 0.44
D 0.08 -0.18
I think faster, if many columns, is use vectorized solution with str.split
and then select first lists
by str[0]
:
print (df.columns.str.split('.'))
Index([['TAN', 'SK'], ['SHA', 'LO']], dtype='object')
df.columns = df.columns.str.split('.').str[0]
print (df)
TAN SHA
A 0.05 0.01
S 0.04 0.44
D 0.08 -0.18
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With