簡體   English   中英

重命名 Pandas 中的列名

[英]Renaming column names in Pandas

我想從

['$a', '$b', '$c', '$d', '$e']

['a', 'b', 'c', 'd', 'e']

重命名特定列

使用df.rename()函數並引用要重命名的列。 並非所有列都必須重命名:

df = df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'})
# Or rename the existing DataFrame (rather than creating a copy) 
df.rename(columns={'oldName1': 'newName1', 'oldName2': 'newName2'}, inplace=True)

最小代碼示例

df = pd.DataFrame('x', index=range(3), columns=list('abcde'))
df

   a  b  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

以下方法都有效並產生相同的輸出:

df2 = df.rename({'a': 'X', 'b': 'Y'}, axis=1)  # new method
df2 = df.rename({'a': 'X', 'b': 'Y'}, axis='columns')
df2 = df.rename(columns={'a': 'X', 'b': 'Y'})  # old method  

df2

   X  Y  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

請記住將結果分配回去,因為修改不是就地的。 或者,指定inplace=True

df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)
df

   X  Y  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x
 

從 v0.25 開始,如果指定了要重命名的無效列,您還可以指定errors='raise'來引發錯誤。 請參閱v0.25 rename()文檔


重新分配列標題

df.set_axis()axis=1inplace=False一起使用(返回副本)。

df2 = df.set_axis(['V', 'W', 'X', 'Y', 'Z'], axis=1, inplace=False)
df2

   V  W  X  Y  Z
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

這將返回一個副本,但您可以通過設置 inplace inplace=True修改 DataFrame(這是版本 <=0.24 的默​​認行為,但將來可能會更改)。

您也可以直接分配標題:

df.columns = ['V', 'W', 'X', 'Y', 'Z']
df

   V  W  X  Y  Z
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

只需將其分配給.columns屬性:

>>> df = pd.DataFrame({'$a':[1,2], '$b': [10,20]})
>>> df
   $a  $b
0   1  10
1   2  20

>>> df.columns = ['a', 'b']
>>> df
   a   b
0  1  10
1  2  20

rename方法可以帶一個函數,例如:

In [11]: df.columns
Out[11]: Index([u'$a', u'$b', u'$c', u'$d', u'$e'], dtype=object)

In [12]: df.rename(columns=lambda x: x[1:], inplace=True)

In [13]: df.columns
Out[13]: Index([u'a', u'b', u'c', u'd', u'e'], dtype=object)

使用文本數據中所述:

df.columns = df.columns.str.replace('$', '')

熊貓 0.21+ 答案

0.21 版中對列重命名進行了一些重大更新。

  • rename方法添加了axis參數,可以設置為columns1 此更新使此方法與 pandas API 的其余部分相匹配。 它仍然具有indexcolumns參數,但您不再被迫使用它們。
  • inplace設置為Falseset_axis方法使您能夠使用列表重命名所有索引或列標簽。

Pandas 0.21+ 的示例

構建示例 DataFrame:

df = pd.DataFrame({'$a':[1,2], '$b': [3,4], 
                   '$c':[5,6], '$d':[7,8], 
                   '$e':[9,10]})

   $a  $b  $c  $d  $e
0   1   3   5   7   9
1   2   4   6   8  10

renameaxis='columns'axis=1一起使用

df.rename({'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'}, axis='columns')

或者

df.rename({'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'}, axis=1)

兩者都導致以下結果:

   a  b  c  d   e
0  1  3  5  7   9
1  2  4  6  8  10

仍然可以使用舊的方法簽名:

df.rename(columns={'$a':'a', '$b':'b', '$c':'c', '$d':'d', '$e':'e'})

rename函數還接受將應用於每個列名的函數。

df.rename(lambda x: x[1:], axis='columns')

或者

df.rename(lambda x: x[1:], axis=1)

set_axis與列表和 inplace inplace=False一起使用

您可以為set_axis方法提供一個長度等於列數(或索引)的列表。 目前, inplace默認為True ,但在未來的版本中, inplace將默認為False

df.set_axis(['a', 'b', 'c', 'd', 'e'], axis='columns', inplace=False)

或者

df.set_axis(['a', 'b', 'c', 'd', 'e'], axis=1, inplace=False)

為什么不使用df.columns = ['a', 'b', 'c', 'd', 'e']

像這樣直接分配列並沒有錯。 這是一個非常好的解決方案。

使用set_axis的優點是它可以用作方法鏈的一部分,並且它返回 DataFrame 的新副本。 沒有它,在重新分配列之前,您必須將鏈的中間步驟存儲到另一個變量中。

# new for pandas 0.21+
df.some_method1()
  .some_method2()
  .set_axis()
  .some_method3()

# old way
df1 = df.some_method1()
        .some_method2()
df1.columns = columns
df1.some_method3()

由於您只想刪除所有列名中的 $ 符號,您可以這樣做:

df = df.rename(columns=lambda x: x.replace('$', ''))

或者

df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

在 Pandas 中重命名列是一項簡單的任務。

df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)
df.columns = ['a', 'b', 'c', 'd', 'e']

它將按照您提供的順序將現有名稱替換為您提供的名稱。

利用:

old_names = ['$a', '$b', '$c', '$d', '$e'] 
new_names = ['a', 'b', 'c', 'd', 'e']
df.rename(columns=dict(zip(old_names, new_names)), inplace=True)

這樣,您可以根據需要手動編輯new_names 當您只需要重命名幾列以糾正拼寫錯誤、重音符號、刪除特殊字符等時,它非常有用。

列名與系列名稱

我想解釋一下幕后發生的事情。

數據框是一組系列。

系列又是numpy.array的擴展。

numpy.array有一個屬性.name

這是該系列的名稱。 Pandas 很少尊重此屬性,但它在某些地方徘徊,可用於破解 Pandas 的某些行為。

命名列列表

這里的很多答案都談到df.columns屬性是一個list ,而實際上它是一個Series 這意味着它有一個.name屬性。

如果您決定填寫Series列的名稱,就會發生這種情況:

df.columns = ['column_one', 'column_two']
df.columns.names = ['name of the list of columns']
df.index.names = ['name of the index']

name of the list of columns     column_one  column_two
name of the index
0                                    4           1
1                                    5           2
2                                    6           3

請注意,索引的名稱總是低一列。

揮之不去的文物

.name屬性有時會持續存在。 如果您設置df.columns = ['one', 'two']那么df.one.name將是'one'

如果你設置df.one.name = 'three'那么df.columns仍然會給你['one', 'two'] ,並且df.one.name會給你'three'

pd.DataFrame(df.one)將返回

    three
0       1
1       2
2       3

因為 Pandas 重用了已經定義的Series.name

多級列名

Pandas 可以使用多層列名。 沒有太多的魔法,但我也想在我的回答中涵蓋這一點,因為我沒有看到有人在這里接受這個。

    |one            |
    |one      |two  |
0   |  4      |  1  |
1   |  5      |  2  |
2   |  6      |  3  |

這很容易通過將列設置為列表來實現,如下所示:

df.columns = [['one', 'one'], ['one', 'two']]

一條線或管道解決方案

我將專注於兩件事:

  1. OP明確指出

    我將編輯后的列名存儲在一個列表中,但我不知道如何替換列名。

    我不想解決如何替換'$'或從每個列標題中刪除第一個字符的問題。 OP 已經完成了這一步。 相反,我想專注於在給定替換列名稱列表的情況下用新的columns對象替換現有的列對象。

  2. df.columns = new其中new是新列名稱的列表,這很簡單。 這種方法的缺點是它需要編輯現有數據框的columns屬性,並且不是內聯完成的。 我將展示一些通過流水線執行此操作的方法,而無需編輯現有數據框。


設置 1
為了專注於用預先存在的列表重命名替換列名的需要,我將創建一個新的示例數據框df ,其中包含初始列名和不相關的新列名。

df = pd.DataFrame({'Jack': [1, 2], 'Mahesh': [3, 4], 'Xin': [5, 6]})
new = ['x098', 'y765', 'z432']

df

   Jack  Mahesh  Xin
0     1       3    5
1     2       4    6

解決方案 1
pd.DataFrame.rename

已經說過,如果您有一個將舊列名映射到新列名的字典,則可以使用pd.DataFrame.rename

d = {'Jack': 'x098', 'Mahesh': 'y765', 'Xin': 'z432'}
df.rename(columns=d)

   x098  y765  z432
0     1     3     5
1     2     4     6

但是,您可以輕松地創建該字典並將其包含在對rename的調用中。 下面利用了這樣一個事實,即在迭代df時,我們迭代每個列名。

# Given just a list of new column names
df.rename(columns=dict(zip(df, new)))

   x098  y765  z432
0     1     3     5
1     2     4     6

如果您的原始列名是唯一的,這將非常有用。 但如果他們不是,那么這就會崩潰。


設置 2
非唯一列

df = pd.DataFrame(
    [[1, 3, 5], [2, 4, 6]],
    columns=['Mahesh', 'Mahesh', 'Xin']
)
new = ['x098', 'y765', 'z432']

df

   Mahesh  Mahesh  Xin
0       1       3    5
1       2       4    6

解決方案 2
pd.concat使用keys參數

首先,注意當我們嘗試使用解決方案 1 時會發生什么:

df.rename(columns=dict(zip(df, new)))

   y765  y765  z432
0     1     3     5
1     2     4     6

我們沒有將new列表映射為列名。 我們最終重復了y765 相反,我們可以在遍歷df的列時使用pd.concat函數的keys參數。

pd.concat([c for _, c in df.items()], axis=1, keys=new) 

   x098  y765  z432
0     1     3     5
1     2     4     6

解決方案 3
重建。 僅當所有列都有一個dtype時才應使用此選項。 否則,您最終會得到所有列的dtype object ,並且將它們轉換回來需要更多的字典工作。

單一dtype

pd.DataFrame(df.values, df.index, new)

   x098  y765  z432
0     1     3     5
1     2     4     6

混合dtype

pd.DataFrame(df.values, df.index, new).astype(dict(zip(new, df.dtypes)))

   x098  y765  z432
0     1     3     5
1     2     4     6

解決方案 4
這是transposeset_index的噱頭。 pd.DataFrame.set_index允許我們內聯設置索引,但沒有對應set_columns 所以我們可以轉置,然后set_index ,然后轉回。 但是,解決方案 3 中相同的單一dtype與混合dtype警告在這里適用。

單一dtype

df.T.set_index(np.asarray(new)).T

   x098  y765  z432
0     1     3     5
1     2     4     6

混合dtype

df.T.set_index(np.asarray(new)).T.astype(dict(zip(new, df.dtypes)))

   x098  y765  z432
0     1     3     5
1     2     4     6

解決方案 5
pd.DataFrame.rename中使用lambda循環遍歷new的每個元素。
在這個解決方案中,我們傳遞了一個接受x但隨后忽略它的 lambda。 它也需要一個y但並不期望它。 相反,將迭代器作為默認值給出,然后我可以使用它一次循環遍歷一個,而無需考慮x的值是什么。

df.rename(columns=lambda x, y=iter(new): next(y))

   x098  y765  z432
0     1     3     5
1     2     4     6

正如sopython chat中的人們向我指出的那樣,如果我在xy之間添加一個* ,我可以保護我的y變量。 不過,在這種情況下,我認為它不需要保護。 仍然值得一提。

df.rename(columns=lambda x, *, y=iter(new): next(y))

   x098  y765  z432
0     1     3     5
1     2     4     6

讓我們通過一個小例子來理解重命名......

  1. 使用映射重命名列:

     df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) # Creating a df with column name A and B df.rename({"A": "new_a", "B": "new_b"}, axis='columns', inplace =True) # Renaming column A with 'new_a' and B with 'new_b' Output: new_a new_b 0 1 4 1 2 5 2 3 6
  2. 使用映射重命名 index/Row_Name:

     df.rename({0: "x", 1: "y", 2: "z"}, axis='index', inplace =True) # Row name are getting replaced by 'x', 'y', and 'z'. Output: new_a new_b x 1 4 y 2 5 z 3 6

假設您的數據集名稱是 df,而 df 有。

df = ['$a', '$b', '$c', '$d', '$e']`

因此,要重命名這些,我們只需這樣做。

df.columns = ['a','b','c','d','e']

假設這是您的數據框。

在此處輸入圖像描述

您可以使用兩種方法重命名列。

  1. 使用dataframe.columns=[#list]

     df.columns=['a','b','c','d','e']

    在此處輸入圖像描述

    此方法的局限性在於,如果必須更改一列,則必須傳遞完整的列列表。 此外,此方法不適用於索引標簽。 例如,如果你通過了這個:

     df.columns = ['a','b','c','d']

    這將引發錯誤。 長度不匹配:預期軸有 5 個元素,新值有 4 個元素。

  2. 另一種方法是 Pandas rename()方法,用於重命名任何索引、列或行

    df = df.rename(columns={'$a':'a'})

    在此處輸入圖像描述

同樣,您可以更改任何行或列。

許多 pandas 函數都有一個 inplace 參數。 將其設置為 True 時,轉換直接應用於您調用它的數據框。 例如:

df = pd.DataFrame({'$a':[1,2], '$b': [3,4]})
df.rename(columns={'$a': 'a'}, inplace=True)
df.columns

>>> Index(['a', '$b'], dtype='object')

或者,在某些情況下,您希望保留原始數據框。 如果創建數據框是一項昂貴的任務,我經常看到人們陷入這種情況。 例如,如果創建數據框需要查詢雪花數據庫。 在這種情況下,只需確保將 inplace 參數設置為 False。

df = pd.DataFrame({'$a':[1,2], '$b': [3,4]})
df2 = df.rename(columns={'$a': 'a'}, inplace=False)
df.columns
    
>>> Index(['$a', '$b'], dtype='object')

df2.columns

>>> Index(['a', '$b'], dtype='object')

如果這些類型的轉換是您經常做的事情,您還可以查看許多不同的 pandas GUI 工具。 我是一個叫做Mito的創造者。 它是一個電子表格,可自動將您的編輯轉換為 python 代碼。

df.rename(index=str, columns={'A':'a', 'B':'b'})

pandas.DataFrame.rename

如果您有數據框,則 df.columns 會將所有內容轉儲到您可以操作的列表中,然后將其作為列名重新分配到您的數據框中...

columns = df.columns
columns = [row.replace("$", "") for row in columns]
df.rename(columns=dict(zip(columns, things)), inplace=True)
df.head() # To validate the output

最好的辦法? 我不知道。 一種方式——是的。

評估問題答案中提出的所有主要技術的更好方法是使用 cProfile 來衡量內存和執行時間。 @kadee、@kaitlyn 和 @eumiro 具有執行時間最快的函數 - 盡管這些函數非常快,但我們正在比較所有答案的 0.000 和 0.001 秒的舍入。 道德:我上面的答案可能不是“最好”的方式。

import pandas as pd
import cProfile, pstats, re

old_names = ['$a', '$b', '$c', '$d', '$e']
new_names = ['a', 'b', 'c', 'd', 'e']
col_dict = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}

df = pd.DataFrame({'$a':[1, 2], '$b': [10, 20], '$c': ['bleep', 'blorp'], '$d': [1, 2], '$e': ['texa$', '']})

df.head()

def eumiro(df, nn):
    df.columns = nn
    # This direct renaming approach is duplicated in methodology in several other answers:
    return df

def lexual1(df):
    return df.rename(columns=col_dict)

def lexual2(df, col_dict):
    return df.rename(columns=col_dict, inplace=True)

def Panda_Master_Hayden(df):
    return df.rename(columns=lambda x: x[1:], inplace=True)

def paulo1(df):
    return df.rename(columns=lambda x: x.replace('$', ''))

def paulo2(df):
    return df.rename(columns=lambda x: x.replace('$', ''), inplace=True)

def migloo(df, on, nn):
    return df.rename(columns=dict(zip(on, nn)), inplace=True)

def kadee(df):
    return df.columns.str.replace('$', '')

def awo(df):
    columns = df.columns
    columns = [row.replace("$", "") for row in columns]
    return df.rename(columns=dict(zip(columns, '')), inplace=True)

def kaitlyn(df):
    df.columns = [col.strip('$') for col in df.columns]
    return df

print 'eumiro'
cProfile.run('eumiro(df, new_names)')
print 'lexual1'
cProfile.run('lexual1(df)')
print 'lexual2'
cProfile.run('lexual2(df, col_dict)')
print 'andy hayden'
cProfile.run('Panda_Master_Hayden(df)')
print 'paulo1'
cProfile.run('paulo1(df)')
print 'paulo2'
cProfile.run('paulo2(df)')
print 'migloo'
cProfile.run('migloo(df, old_names, new_names)')
print 'kadee'
cProfile.run('kadee(df)')
print 'awo'
cProfile.run('awo(df)')
print 'kaitlyn'
cProfile.run('kaitlyn(df)')
df = pd.DataFrame({'$a': [1], '$b': [1], '$c': [1], '$d': [1], '$e': [1]})

如果您的新列列表與現有列的順序相同,則分配很簡單:

new_cols = ['a', 'b', 'c', 'd', 'e']
df.columns = new_cols
>>> df
   a  b  c  d  e
0  1  1  1  1  1

如果您有一個將舊列名鍵入新列名的字典,則可以執行以下操作:

d = {'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}
df.columns = df.columns.map(lambda col: d[col])  # Or `.map(d.get)` as pointed out by @PiRSquared.
>>> df
   a  b  c  d  e
0  1  1  1  1  1

如果您沒有列表或字典映射,則可以通過列表推導去除前導$符號:

df.columns = [col[1:] if col[0] == '$' else col for col in df]

我們可以替換原始列標簽的另一種方法是從原始列標簽中刪除不需要的字符(此處為“$”)。

這可以通過在 df.columns 上運行for循環並將剝離的列附加到 df.columns 來完成。

相反,我們可以使用下面的列表推導在單個語句中巧妙地做到這一點:

df.columns = [col.strip('$') for col in df.columns]

( Python 中的strip方法從字符串的開頭和結尾剝離給定的字符。)

這真的很簡單。 只需使用:

df.columns = ['Name1', 'Name2', 'Name3'...]

它將按照您輸入的順序分配列名。

如果您已經有了新列名的列表,可以試試這個:

new_cols = ['a', 'b', 'c', 'd', 'e']
new_names_map = {df.columns[i]:new_cols[i] for i in range(len(new_cols))}

df.rename(new_names_map, axis=1, inplace=True)
# This way it will work
import pandas as pd

# Define a dictionary 
rankings = {'test': ['a'],
        'odi': ['E'],
        't20': ['P']}

# Convert the dictionary into DataFrame
rankings_pd = pd.DataFrame(rankings)

# Before renaming the columns
print(rankings_pd)

rankings_pd.rename(columns = {'test':'TEST'}, inplace = True)

你可以使用str.slice

df.columns = df.columns.str.slice(1)

另一種選擇是使用正則表達式重命名:

import pandas as pd
import re

df = pd.DataFrame({'$a':[1,2], '$b':[3,4], '$c':[5,6]})

df = df.rename(columns=lambda x: re.sub('\$','',x))
>>> df
   a  b  c
0  1  3  5
1  2  4  6

我的方法是通用的,您可以通過逗號分隔delimiters= variable 添加其他分隔符並使其面向未來。

工作代碼:

import pandas as pd
import re


df = pd.DataFrame({'$a':[1,2], '$b': [3,4],'$c':[5,6], '$d': [7,8], '$e': [9,10]})

delimiters = '$'
matchPattern = '|'.join(map(re.escape, delimiters))
df.columns = [re.split(matchPattern, i)[1] for i in df.columns ]

輸出:

>>> df
   $a  $b  $c  $d  $e
0   1   3   5   7   9
1   2   4   6   8  10

>>> df
   a  b  c  d   e
0  1  3  5  7   9
1  2  4  6  8  10

請注意,先前答案中的方法不適用於MultiIndex 對於MultiIndex ,您需要執行以下操作:

>>> df = pd.DataFrame({('$a','$x'):[1,2], ('$b','$y'): [3,4], ('e','f'):[5,6]})
>>> df
   $a $b  e
   $x $y  f
0  1  3  5
1  2  4  6
>>> rename = {('$a','$x'):('a','x'), ('$b','$y'):('b','y')}
>>> df.columns = pandas.MultiIndex.from_tuples([
        rename.get(item, item) for item in df.columns.tolist()])
>>> df
   a  b  e
   x  y  f
0  1  3  5
1  2  4  6

如果您必須處理您無法控制的由提供系統命名的大量列,我想出了以下方法,它是一種通用方法和特定替換的組合。

首先使用正則表達式從數據框列名創建一個字典,以便丟棄列名的某些附錄,然后將特定替換添加到字典中,以便稍后在接收數據庫中按預期命名核心列。

然后將其一次性應用於數據幀。

dict = dict(zip(df.columns, df.columns.str.replace('(:S$|:C1$|:L$|:D$|\.Serial:L$)', '')))
dict['brand_timeseries:C1'] = 'BTS'
dict['respid:L'] = 'RespID'
dict['country:C1'] = 'CountryID'
dict['pim1:D'] = 'pim_actual'
df.rename(columns=dict, inplace=True)

如果您只想刪除“$”符號,請使用以下代碼

df.columns = pd.Series(df.columns.str.replace("$", ""))

除了已經提供的解決方案之外,您還可以在讀取文件時替換所有列。 我們可以使用namesheader=0來做到這一點。

首先,我們創建一個我們喜歡用作列名的名稱列表:

import pandas as pd

ufo_cols = ['city', 'color reported', 'shape reported', 'state', 'time']
ufo.columns = ufo_cols

ufo = pd.read_csv('link to the file you are using', names = ufo_cols, header = 0)

在這種情況下,所有列名都將替換為您在列表中的名稱。

這是我喜歡用來減少打字的一個漂亮的小功能:

def rename(data, oldnames, newname):
    if type(oldnames) == str: # Input can be a string or list of strings
        oldnames = [oldnames] # When renaming multiple columns
        newname = [newname] # Make sure you pass the corresponding list of new names
    i = 0
    for name in oldnames:
        oldvar = [c for c in data.columns if name in c]
        if len(oldvar) == 0:
            raise ValueError("Sorry, couldn't find that column in the dataset")
        if len(oldvar) > 1: # Doesn't have to be an exact match
            print("Found multiple columns that matched " + str(name) + ": ")
            for c in oldvar:
                print(str(oldvar.index(c)) + ": " + str(c))
            ind = input('Please enter the index of the column you would like to rename: ')
            oldvar = oldvar[int(ind)]
        if len(oldvar) == 1:
            oldvar = oldvar[0]
        data = data.rename(columns = {oldvar : newname[i]})
        i += 1
    return data

這是它如何工作的示例:

In [2]: df = pd.DataFrame(np.random.randint(0, 10, size=(10, 4)), columns = ['col1', 'col2', 'omg', 'idk'])
# First list = existing variables
# Second list = new names for those variables
In [3]: df = rename(df, ['col', 'omg'],['first', 'ohmy'])
Found multiple columns that matched col:
0: col1
1: col2

Please enter the index of the column you would like to rename: 0

In [4]: df.columns
Out[5]: Index(['first', 'col2', 'ohmy', 'idk'], dtype='object')

假設您可以使用正則表達式,此解決方案無需使用正則表達式進行手動編碼:

import pandas as pd
import re

srch = re.compile(r"\w+")

data = pd.read_csv("CSV_FILE.csv")
cols = data.columns
new_cols = list(map(lambda v:v.group(), (list(map(srch.search, cols)))))
data.columns = new_cols

我需要重命名 XGBoost 的功能,但它不喜歡以下任何一個:

import re
regex = r"[!\"#$%&'()*+,\-.\/:;<=>?@[\\\]^_`{|}~ ]+"
X_trn.columns = X_trn.columns.str.replace(regex, '_', regex=True)
X_tst.columns = X_tst.columns.str.replace(regex, '_', regex=True)

您可以使用帶有索引的lstripstrip方法:

df.columns = df.columns.str.lstrip('$')

或者

cols = ['$a', '$b', '$c', '$d', '$e']
pd.Series(cols).str.lstrip('$').tolist()

輸出:

['a', 'b', 'c', 'd', 'e']

我的單行答案是df.columns = df_new_cols是處理時間為 1/3 的最佳答案。

timeit比較:df 有 7 列。 我正在嘗試更改一些名稱。

%timeit df.rename(columns={old_col:new_col for (old_col,new_col) in zip(df_old_cols,df_new_cols)},inplace=True)
214 µs ± 10.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.rename(columns=dict(zip(df_old_cols,df_new_cols)),inplace=True)
212 µs ± 7.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit df.columns = df_new_cols
72.9 µs ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM