Ben
Ben

Reputation: 47

How to get the first digits from a column name?

my column names are 22abcd123, 33sdfjsdh77, 45hgvjh77, 44vhsfgdhd88 i need my column name as 22,33,45,44.

I tried: res = int(re.findall('(\d+)',df.columns[5])[0]) i got the answer for 1 column name . but I need it for every column name in a Dataframe

Upvotes: 1

Views: 123

Answers (2)

mozway
mozway

Reputation: 260640

You can use:

df.columns = df.columns.str.extract('(\d+)', expand=False)

Upvotes: 1

TheDataScienceNinja
TheDataScienceNinja

Reputation: 126

First you can get all of your column names as an array using:

myArray = pandas.columns(df)

Now you have an array of column names in myArray

Now write a loop to get your new column names and add the new column names to an array:

newArray = []
for i in myArray:
     newColName = myArray[i][0:2]
     newArray = newArray.append(newColName)
     i=i+1

Upvotes: 0

Related Questions