我有以下系列,想a1用a、b1和替換。bc1c
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
有沒有更好的方法來做到這一點?我假設 pandas 有一個內置的功能。
我試過了replace,但它沒有幫助。
data.replace['a1', 'a']
data.replace['b1', 'c']
data.replace['c1', 'c']
感謝您提前發表任何評論。
uj5u.com熱心網友回復:
創建字典以替換和使用串列理解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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446225.html
