1

I have some tables from the Bureau of Labor Statistics that I converted to cvs files in Python. The 'Item' column has some rows with multiple '.' . I'm trying to iterate through these rows and replace these '.' with '' .

I've tried:

for row in age_df_1989['Item']:
   if '.' in row:
      age_df_1989['Item'].replace('.','')

Any ideas on what I can do for this?

3 Answers 3

2

No assigning age_df_1989['Item'].replace('.','') to a variable won't change the original data, you need to do this:

for row in age_df_1989['Item']:
   if '.' in row:
      row['Item'] = row['Item'].replace('.','')
Sign up to request clarification or add additional context in comments.

Comments

0

Try apply

age_df_1989['Item'] = age_df_1989['Item'].apply(lambda x: x.replace('.', '')

Simple & faster than a for loop

Comments

0

Use the vectorised str method replace: This is much faster than the iterrows or for loop or apply option.

You can do something as simple as

df['column name'] = df['column name'].str.replace('old value','new value')

For your example, do this:

age_df_1989['Item'] = age_df_1989['Item'].str.replace('.', '')

Here's an example output of this:

c = ['Name','Item']
d = [['Bob','Good. Bad. Ugly.'],
     ['April','Today. Tomorrow'],
     ['Amy','Grape. Peach. Banana.'],
     ['Linda','Pink. Red. Yellow.']]
import pandas as pd
age_df_1989 = pd.DataFrame(d, columns = c)
print (age_df_1989)
age_df_1989['Item'] = age_df_1989['Item'].str.replace('.', '')
print (age_df_1989)

Dataframe: age_df_1989 : Original

    Name                   Item
0    Bob       Good. Bad. Ugly.
1  April        Today. Tomorrow
2    Amy  Grape. Peach. Banana.
3  Linda     Pink. Red. Yellow.

Dataframe: age_df_1989 : After the replace command

    Name                Item
0    Bob       Good Bad Ugly
1  April      Today Tomorrow
2    Amy  Grape Peach Banana
3  Linda     Pink Red Yellow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.