简体   繁体   中英

How to Replace values in a pd dataframe column based on a condition with a range of values?

I have a data set which has a column name 'id'. Now in this column all the values should be 1 to 696 in sequence, but values after 636 are 7*** something, I want to replace all these values and bring them in range 637 to 696. How can I do that? I tried replace, .loc, where etc. but it doesn't work.

Simply do

import pandas as pd 

df = pd.read_csv('input.csv')
df['id'] = range(1,len(df)+1)

if you want it to start on 0, do:

df['id'] = range(len(df))

Simply, re-assign id for sequential integers using numpy.arange :

df = (pd.read_csv("/path/to/data.csv")
        .assign(id = np.arange(1,697))
     )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM