在Pandas中,如何替换Series中的列表元素



我有以下系列,希望用a替换a1,用b替换b1,用c替换c1

data = pd.Series([['a1', 'b1', 'c1'], ['b1', 'a1', 'c1'], ['c1', 'a1' ,'b1']])
Out[132]: 
0    [a1, b1, c1]
1    [b1, a1, c1]
2    [c1, a1, b1]
dtype: object

预期结果如下。

0    [a, b, c]
1    [b, a, c]
2    [c, a, b]
dtype: object

下面的代码做了我想做的事情,但这似乎不是一个很好的方法

for i, s in enumerate(data):
temp = ['a' if x == 'a1' else x for x in s]
temp = ['b' if x == 'b1' else x for x in temp]
temp = ['c' if x == 'c1' else x for x in temp]
data.iloc[i] = temp

有更好的方法吗?我想熊猫有一个内置的功能。

我用replace试过,但没有用。

data.replace['a1', 'a']
data.replace['b1', 'c']
data.replace['c1', 'c']

感谢您提前发表评论。

创建字典,用get替换和使用列表理解-第二个参数y如果不存在,则获取原始密钥:

d = {'a1':'a', 'b1':'b', 'c1':'c'}
data = data.apply(lambda x: [d.get(y,y) for y in x])
#alternative solution
#data = data.map(lambda x: [d.get(y,y) for y in x])
print (data)
0    [a, b, c]
1    [b, a, c]
2    [c, a, b]
dtype: object

或者:

data = pd.Series([[d.get(y,y) for y in x] for x in data], index=data.index)

如果性能不重要:

data = data.explode().replace(d).groupby(level=0).agg(list)
print (data)
0    [a, b, c]
1    [b, a, c]
2    [c, a, b]
dtype: object

最新更新