Skip to content
Advertisement

How to replace several values of a column using lists in python

I have a dataframe name “detalhe” with several columns and one is named: “Concelho”. I have a list of unique values of “Concelho” named “Concelho ADENE” and I would like to replace each occurrence with a different list called “INE”.

    Concelho ADENE  INE
0   ABRANTES    Abrantes
1   AGUEDA  Águeda
2   AGUIAR DA BEIRA Aguiar da Beira
3   ALANDROAL   Alandroal
4   ALBERGARIA-A-VELHA  Albergaria-a-Velha
... ... ...
284 VIMIOSO Vimioso
285 VINHAIS Vinhais

Both lists have the same length and each entrance correspond (they are alphanumeric sorted) (I also have a csv file with both lists as 2 parallels columns.)

I tried:

detalhe= pd.read_csv('Detalhe.csv')
detalhe['Concelho'].replace(Concelho ADENE,INE)
detalhe

AttributeError: 'Series' object has no attribute '_replace_columnwise'

Advertisement

Answer

could you please provide a sample code(like below) to check to reproduce the scenario? replacing using list is working fine

df = pd.DataFrame({'A': [0, 1, 2, 3, 4],
                   'B': [5, 6, 7, 8, 9],
                   'C': ['a', 'b', 'c', 'd', 'e']})                  
print(df)
print("-----------")

init = [7,6,9]
final = [17,16,19]
df.B.replace(init,final,inplace=True)
print(df)

output:

A  B  C
0  0  5  a
1  1  6  b
2  2  7  c
3  3  8  d
4  4  9  e
-----------
A   B  C
0  0   5  a
1  1  16  b
2  2  17  c
3  3   8  d
4  4  19  e
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement