Python:剥离成对的列名

Python: strip pair-wise column names

我有一个 DataFrame,其列如下所示:

df=pd.DataFrame(columns=['(NYSE_close, close)','(NYSE_close, open)','(NYSE_close, volume)', '(NASDAQ_close, close)','(NASDAQ_close, open)','(NASDAQ_close, volume)'])

df:
(NYSE_close, close) (NYSE_close, open) (NYSE_close, volume) (NASDAQ_close, close) (NASDAQ_close, open) (NASDAQ_close, volume)

我想删除下划线后的所有内容并附加逗号后的所有内容以获得以下内容:

df:
NYSE_close  NYSE_open  NYSE_volume  NASDAQ_close  NASDAQ_open  NASDAQ_volume

我试图去掉列名,但它用 nan 代替了它。关于如何做到这一点有什么建议吗?

提前致谢。

您可以使用 re.sub 来提取列名称的适当部分以将它们替换为:

import re

df=pd.DataFrame(columns=['(NYSE_close, close)','(NYSE_close, open)','(NYSE_close, volume)', '(NASDAQ_close, close)','(NASDAQ_close, open)','(NASDAQ_close, volume)'])
df.columns = [re.sub(r'\(([^_]+_)\w+, (\w+)\)', r'', c) for c in df.columns]

输出:

Empty DataFrame
Columns: [NYSE_close, NYSE_open, NYSE_volume, NASDAQ_close, NASDAQ_open, NASDAQ_volume]
Index: []

你可以:

import re

def cvt_col(x):
    s = re.sub('[()_,]', ' ', x).split()
    return s[0] + '_' + s[2] 

df.rename(columns = cvt_col)

Empty DataFrame
Columns: [NYSE_close, NYSE_open, NYSE_volume, NASDAQ_close, NASDAQ_open, NASDAQ_volume]
Index: []

使用列表理解,两次:

step1 = [ent.strip('()').split(',') for ent  in df]

df.columns = ["_".join([left.split('_')[0], right.strip()]) 
              for left, right  in step1]

df

Empty DataFrame
Columns: [NYSE_close, NYSE_open, NYSE_volume, NASDAQ_close, NASDAQ_open, NASDAQ_volume]
Index: []