简体   繁体   中英

How to edit all values of a column in a pandas dataframe?

I am trying to edit all the values in a specific column ( 'ISSN1' ) of a dataframe ( df1 ) in pandas. An example value of this column is 1234-5678 and I would like it to be modified in order to remove the - (thus obtaining 12345678 ).

If I do this:

print(df1)

for elem in df1.ISSN1:
    elem = str(elem).replace("-", "")

print(df1)

The dataframe results in being apparently unchanged and I get no error message. Why? How can I remove the dash in all values of the 'ISSN1' column? Notice that some values are NaN .

I found some answers using lambdas but I find it a little confusing and since I am still learning I would prefer an answer that doesn't include lambdas.

You can use apply :

df1['ISSN1'] = df1['ISSN1'].apply(lambda x: str(x).replace('-', '')

Or pd.Series.str method:

df1['ISSN1'] = df1['ISSN1'].astype(str).str.replace('-', '')

If your column contains only strings and possibly np.nan you can remove astype(str) :

df1['ISSN1'] = df1['ISSN1'].str.replace('-', '')

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