0

I have a data frame:

df = pd.DataFrame({"id": [1,2,3], "2000": ['p', 'w', nan], "2001": ['p', 'p', nan], "2002": ['p', nan, 'p']})

id  2000 2001 2002
1    p    p     p
2    w    p     nan
3    nan  nan   p

I want to replace all the 'p' and 'w' by '1'.

I applied :

df['2000'] = df['2000'].str.replace('p','1')
df['2000'] = df['2000'].str.replace('w','1')

df['2001'] = df['2001'].str.replace('p','1')
df['2001'] = df['2001'].str.replace('w','1')

and so on for each year and it is working.

id  2000 2001 2002
1    1    1     1
2    1    1     nan
3    nan  nan   1


Since, I have a very long data, I am wondering whether there any alternative command, that I can use for the entire data-frame, instead of coding for each column.

Jui Sen
  • 377
  • 3
  • 12
  • Does this answer your question? [Remap values in pandas column with a dict](https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict) – gold_cy Jun 08 '21 at 19:40
  • 1
    `df.set_index('id').replace('p', '1').reset_index()`? – It_is_Chris Jun 08 '21 at 19:42
  • @gold_cy it gives me the same long procedure. – Jui Sen Jun 08 '21 at 19:49
  • creating a dictionary to remap values is a long procedure? what if different letters need different values... – gold_cy Jun 08 '21 at 19:52
  • @gold-cy, I already said that I have a large number of column for like 50 years and I know how to do it separately for each column, the link that u have provided me , it also requires to replace for each column. I hope you understand and I appreciate your response. – Jui Sen Jun 08 '21 at 19:55
  • you're missing the point, best of luck since it seems you did not _properly_ read that link – gold_cy Jun 08 '21 at 20:04

1 Answers1

4
>>> df.replace({r'[pw]': 1}, regex=True)
   id  2000  2001  2002
0   1   1.0   1.0   1.0
1   2   1.0   1.0   NaN
2   3   NaN   NaN   1.0
Corralien
  • 109,409
  • 8
  • 28
  • 52