1 回答

TA貢獻1877條經驗 獲得超1個贊
對于feat,由于您已經在其他 StackOverflow 問題中得到了答案agg,我認為您可以使用以下內容根據兩個不同的模式提取兩個不同的系列,這些模式彼此分開|,然后fillna()一個系列與另一個系列分開。
^([^A-Z]*$)僅當完整字符串為小寫時才返回完整字符串
[^a-z].*example\.([a-z]+)\).*$example.僅當之前的)字符串中有大寫字母時才應返回之后和之前的字符串example.
df = pd.DataFrame({'item': ['num','bool', 'cat', 'cat.COUNT(example)','cat.N_MOST_COMMON(example.ord)[2]','cat.FIRST(example.ord)','cat.FIRST(example.num)']})
s = df['item'].str.extract('^([^A-Z]*$)|[^a-z].*example\.([a-z]+)\).*$', expand=True)
df['feat'] = s[0].fillna(s[1]).fillna('')
df
Out[1]:
item feat
0 num num
1 bool bool
2 cat cat
3 cat.COUNT(example)
4 cat.N_MOST_COMMON(example.ord)[2] ord
5 cat.FIRST(example.ord) ord
6 cat.FIRST(example.num) num
上面給出了您正在尋找樣本數據的輸出,并符合您的條件。然而:
如果后面有大寫怎么辦example.?電流輸出將返回''
請參見下面的示例#2,其中一些數據根據上述點進行了更改:
df = pd.DataFrame({'item': ['num','cat.count(example.AAA)', 'cat.count(example.aaa)', 'cat.count(example)','cat.N_MOST_COMMON(example.ord)[2]','cat.FIRST(example.ord)','cat.FIRST(example.num)']})
s = df['item'].str.extract('^([^A-Z]*$)|[^a-z].*example\.([a-z]+)\).*$', expand=True)
df['feat'] = s[0].fillna(s[1]).fillna('')
df
Out[2]:
item feat
0 num num
1 cat.count(example.AAA)
2 cat.count(example.aaa) cat.count(example.aaa)
3 cat.count(example) cat.count(example)
4 cat.N_MOST_COMMON(example.ord)[2] ord
5 cat.FIRST(example.ord) ord
6 cat.FIRST(example.num) num
添加回答
舉報