[英]Extract unique exact string matches on data frame column
說我有(具有許多列的微小數據子集)
import pandas as pd
import numpy as np
df = pd.DataFrame({'A (quarterly) 2010': np.random.rand(3),
'A (quarterly) 2011': np.random.rand(3),
'B (quarterly) 2010': np.random.rand(3),
'B (quarterly) 2011': np.random.rand(3),
'X' : np.random.randint(3, size=3)})
#Out[11]:
# A (quarterly) 2010 A (quarterly) 2011 B (quarterly) 2010 \
#0 0.868228 0.300513 0.658819
#1 0.383907 0.496740 0.347421
#2 0.284787 0.795499 0.856398
# B (quarterly) 2011 X
#0 0.374479 1
#1 0.812860 0
#2 0.604731 2
我想在與特定模式f.ex [AB] \\(.*\\)\\s
匹配的列名稱中提取唯一匹配項。
我可以做到,但是看起來很毛茸茸:
stubs = set([match[0] for match in df.columns.str.findall('[A-B] \(.*\) ').values if match != [] ])
list(stubs)
#['B (quarterly) ', 'A (quarterly) ']
有沒有更簡單的方法可以做到這一點?
這是另一種方式,仍然有些毛茸茸,但更加優雅:
def match(x):
m = re.findall(r'[A-B] \(.*\)\s',x)
return m[0] if m else None
[stub for stub in df.columns.to_series().apply(match).unique() if stub]
# ['A (quarterly) ', 'B (quarterly) ']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.