## 如何映射值到位？内容来源于 Stack Overflow，并遵循CC BY-SA 3.0许可协议进行翻译与使用

• 回答 (2)
• 关注 (0)
• 查看 (8)

``````df = pd.DataFrame({'c1': list('aba'), 'c2': list('aaa'), 'ignore_me': list('bbb'), 'c3': list('baa')})

c1 c2 ignore_me c3
0  a  a         b  b
1  b  a         b  a
2  a  a         b  a
``````

``````d = {'a': "foo", 'b': 'bar'}
``````

``````df.filter(regex='^c\d+\$').apply(lambda x: x.map(d))

c1   c2   c3
0  foo  foo  bar
1  bar  foo  foo
2  foo  foo  foo
``````

``````tempdf = df.filter(regex='^c\d+\$')

df.loc[:, tempdf.columns] = tempdf.apply(lambda x: x.map(d))
``````

``````    c1   c2 ignore_me   c3
0  foo  foo         b  bar
1  bar  foo         b  foo
2  foo  foo         b  foo
``````

### 2 个回答

`df.filter(regex='^c\d+\$').apply(lambda x: x.replace(d))`

``````# Your code
df = pd.DataFrame({'c1': list('aba'), 'c2': list('aaa'), 'ignore_me': list('bbb'), 'c3': list('baa')})
d = {'a': "foo", 'b': 'bar'}

# Solution
import re

# Pre-compile the regex object in case there is a huge list of columns....
regex = re.compile(r'^c\d+\$')

# Python 3's `filter` returns a `generator`, add a `list` wrapper to get the columns
cols = list(filter(regex.search, df.columns))
# output ['c1', 'c2', 'c']

df[cols] = df.filter(cols).apply(lambda x: x.map(d))
``````