Home > Blockchain >  How to get the first digits from a column name?
How to get the first digits from a column name?

Time:11-05

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

CodePudding user response:

You can use:

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

CodePudding user response:

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
  • Related