0

For example if this is my Dataframe (all values are str type):

    Random  Random2  Random3    
0   WNNX01  319845   6109100104 
1   WNNX01  319850   6205200002 
2   WNNX01  319865   6403990062 
3   WNNX01  319868   6109901000
4   WNNX01  319888   6204422000

How do I get rid of the last character in all values for "Random3" column? I want the result to look like this:

    Random  Random2  Random3    
0   WNNX01  319845   610910010  
1   WNNX01  319850   620520000  
2   WNNX01  319865   640399006  
3   WNNX01  319868   610990100
4   WNNX01  319888   620442200

This will work but it takes forever with millions of rows (been running for 15mins still not done):

for i in range(len(df)):
    df['Random3'][i] = df['Random3'][i][:-1]

What's a better way?

JYCH
  • 61
  • 7
  • 4
    `df['Random3'] = df['Random3'].str[:-1]` – It_is_Chris Apr 02 '20 at 20:10
  • Does this answer your question? [Pandas make new column from string slice of another column](https://stackoverflow.com/questions/25789445/pandas-make-new-column-from-string-slice-of-another-column) – AMC Apr 02 '20 at 20:18

1 Answers1

1

Try this. It would be more efficient than your code.

df['Random3'] = df['Random3'].astype(str).str.slice(start = 0, stop = -1)

Because the code makes 'Random3' column string, you can change the type using astype function as follows.

df['Random3'] = df['Random3'].astype(int)
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11