7

这里的场景是我有一个df包含原始整数数据的数据框,以及一个map_array将这些整数映射到字符串值的字典。

我需要用地图中的相应值替换数据框中的值,但如果它没有映射到任何东西,则保留原始值。

到目前为止,我能够弄清楚如何做我想做的唯一方法是使用临时列。但是,由于我正在使用的数据量很大,这有时会变得有点麻烦。所以,我想知道在熊猫中是否有一些技巧可以在不需要临时列的情况下做到这一点......

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(1,5, size=(100,1)))
map_array = {1:'one', 2:'two', 4:'four'}

df['__temp__'] = df[0].map(map_array, na_action=None) 
#I've tried varying the na_action arg to no effect

nan_index = data['__temp__'][df['__temp__'].isnull() == True].index
df['__temp__'].ix[nan_index] = df[0].ix[nan_index]
df[0] = df['__temp__']
df = df.drop(['__temp__'], axis=1)
4

1 回答 1

12

我认为您可以简单地使用.replace,无论是在 aDataFrame还是 a Series

>>> df = pd.DataFrame(np.random.randint(1,5, size=(3,3)))
>>> df
   0  1  2
0  3  4  3
1  2  1  2
2  4  2  3
>>> map_array = {1:'one', 2:'two', 4:'four'}
>>> df.replace(map_array)
      0     1    2
0     3  four    3
1   two   one  two
2  four   two    3
>>> df.replace(map_array, inplace=True)
>>> df
      0     1    2
0     3  four    3
1   two   one  two
2  four   two    3

不过,我不确定更改列 dtypes 的内存影响是什么。

于 2013-11-12T02:54:58.283 回答