joeysprite
joeysprite

Reputation: 38

For Loop not writing into DataFrame (Python)

I am trying to analyze some NBA data. I have a CSV file with data and a field called "team" that has the team names and the place they finished in concatenated together in the same field. I tried to write a for loop (below) to look at the final character and if it is a digit. For example, the Boston Celtics that finished in 2nd place would show up as "Boston Celtics2". Another example would be "New York Knicks11".

for x in nba['team']:
        while x[-1].isdigit():
            print(x)
            x = x[:len(x)-1]
            print(x)

I included the print statements to make sure that it is slicing the data properly (which it is). But it is not writing back into my dataframe. Why isn't it storing this back into my dataframe?

Upvotes: 1

Views: 117

Answers (2)

Corralien
Corralien

Reputation: 120391

>>> nba
                  team
0      Boston Celtics2
1    New York Knicks11
2  Los Angeles Lakers7

Remove trailing digits by ''.

nba['team'] = nba['team'].str.replace('\d+$', '')
>>> nba
                 team
0      Boston Celtics
1     New York Knicks
2  Los Angeles Lakers

Upvotes: 1

pssngr
pssngr

Reputation: 21

It is not overwriting your DataFrame because in your for loop x only stores a copy of the value in your nba DataFrame. To change the value in your DataFrame you could loop with an index and change nba at the specific index:

for i, row in nba.iterrows():
    x = row['team'];
    while x[-1].isdigit():
        print(x)
        x = x[:len(x)-1]
        print(x)
    nba.at[i, 'team'] = x

Upvotes: 0

Related Questions