我有一个这样的数据帧:
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'}
现在,我希望将d
的值map
到与regex
^c\d+$
匹配的列。
我能做到
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
是否有更智能的解决方案可以避免tempory数据帧?
发布于 2019-06-03 06:27:46
也许不是最聪明的方式,但我认为这是相当巧妙的……
# 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 # cs95 provided a better solution to pick columns!
# 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', 'c3']
# PICK one of the following...:
# The normal way
df[cols] = df[cols].apply(lambda x: x.map(d))
# OR use `applymap`
df[cols] = df[cols].applymap(lambda x: d[x])
# OR if you prefer not to see `lambda` at all!
df[cols] = df[cols].applymap(d.get)
df
发布于 2019-06-03 06:35:40
https://stackoverflow.com/questions/56419136
复制相似问题