其中col1contains<后跟任意數量的空格和任意數字,我想設定col2為數字。
這是一個示例資料框:
d = {'col1': ['62', '4 < s', '5<77', '< 10 '], 'col2': [3, 4, None, 9]}
df = pd.DataFrame(data=d)
col1 col2
0 62 3.0
1 4 < s 4.0
2 5<77 NaN
3 < 10 9.0
此代碼正確提取模式后我想要的數字:
df['col1'].str.extract(r'<\s*(\d )')
0 NaN
1 NaN
2 77
3 10
但是,當我嘗試col2在陳述句中設定該行時loc,結果出乎意料。如果條件為真,則設定col2為空。
df.loc[(df['col1'].str.contains(r'<\s*\d ')),
'col2'] = df['col1'].str.extract(r'<\s*(\d )')
col1 col2
0 62 3.0
1 4 < s 4.0
2 5<77 NaN
3 < 10 NaN
更令人困惑的是在我的用例中,col2將由字串組成。當我進行此更改并運行相同的代碼時,我得到一個 ValueError:
d = {'col1': ['62', '4 < s', '5<77', '< 10 '], 'col2': ['3', '4', None, '9']}
df = pd.DataFrame(data=d)
df.loc[(df['col1'].str.contains(r'<\s*\d ')),
'col2'] = df['col1'].str.extract(r'<\s*(\d )')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/var/folders/4w/zhsn7cr924bdcsncw_23jrf80000gn/T/ipykernel_88905/3527715470.py in <module>
----> 1 df.loc[(df['col1'].str.contains(r'<\s*\d ')),
2 'col2'] = df['col1'].str.extract(r'<\s*(\d )')
3 df
~/.pyenv/versions/3.9.4/envs/venv-slp2/lib/python3.9/site-packages/pandas/core/indexing.py in __setitem__(self, key, value)
721
722 iloc = self if self.name == "iloc" else self.obj.iloc
--> 723 iloc._setitem_with_indexer(indexer, value, self.name)
724
725 def _validate_key(self, key, axis: int):
~/.pyenv/versions/3.9.4/envs/venv-slp2/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_with_indexer(self, indexer, value, name)
1730 self._setitem_with_indexer_split_path(indexer, value, name)
1731 else:
-> 1732 self._setitem_single_block(indexer, value, name)
1733
1734 def _setitem_with_indexer_split_path(self, indexer, value, name: str):
~/.pyenv/versions/3.9.4/envs/venv-slp2/lib/python3.9/site-packages/pandas/core/indexing.py in _setitem_single_block(self, indexer, value, name)
1960
1961 elif isinstance(value, ABCDataFrame) and name != "iloc":
-> 1962 value = self._align_frame(indexer, value)
1963
1964 # check for chained assignment
~/.pyenv/versions/3.9.4/envs/venv-slp2/lib/python3.9/site-packages/pandas/core/indexing.py in _align_frame(self, indexer, df)
2199 return val
2200
-> 2201 raise ValueError("Incompatible indexer with DataFrame")
2202
2203
ValueError: Incompatible indexer with DataFrame
uj5u.com熱心網友回復:
.str.extract回傳一個資料框,您可能需要從中提取第一列
df.loc[m, 'col2'] = df['col1'].str.extract(r'<\s*(\d )')[0]
uj5u.com熱心網友回復:
Series.str.extract當找不到匹配項時,有一種簡單的方法可以保留原始列值:使用.fillna(df[your_new_col_name]).
您可以使用
df['col2'] = df['col1'].str.extract(r'<\s*(\d )')[0].fillna(df['col2'])
查看 Pandas 測驗:
import pandas as pd
d = {'col1': ['62', '4 < s', '5<77', '< 10 '], 'col2': [3, 4, None, 9]}
df = pd.DataFrame(data=d)
df['col2'] = df['col1'].str.extract(r'<\s*(\d )')[0].fillna(df['col2'])
輸出:
>>> df
col1 col2
0 62 3.0
1 4 < s 4.0
2 5<77 77
3 < 10 10
筆記
type(df['col1'].str.extract(r'<\s*(\d )'))輸出<class 'pandas.core.frame.DataFrame'>,您需要使用[0]索引提取第一列值.fillna(df['col2'])用 的原始值填充 NA 值col2。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/491478.html
上一篇:匹配最近/上個月的正則運算式
