0
data = [['Tom', '5-123g'], ['Max', '6-745.0d'], ['Bob', '5-900.0e'], ['Ben', '2-345',], ['Eva', '9-712.x']]
df = pd.DataFrame(data, columns=['Person', 'Action'])

I want to shorten the "Action" column to a length of 5. My current df has two columns:

['Person'] and ['Action'] 

I need it to look like this:

 person     Action      Action_short      
0    Tom     5-123g      5-123     
1    Max     6-745.0d    6-745 
2    Bob     5-900.0e    5-900  
3    Ben     2-345       2-345 
4    Eva     9-712.x     9-712

What I´ve tried was: Checking the type of the Column

df['Action'].dtypes

The output is: dtype('0') Then I tried:

df['Action'] = df['Action'].map(str)
df['Action_short'] = df.Action.str.slice(start=0, stop=5)

I also tried it with:

df['Action'] = df['Action'].astype(str)
df['Action'] = df['Action'].values.astype(str)
df['Action'] = df['Action'].map(str)
df['Action'] = df['Action'].apply(str)```

and with:

df['Action_short'] = df.Action.str.slice(0:5)
df['Action_short'] = df.Action.apply(lambda x: x[:5])

df['pos'] = df['Action'].str.find('.')
df['new_var'] = df.apply(lambda x: x['Action'][0:x['pos']],axis=1)

The output from all my versions was:

 person     Action      Action_short      
0    Tom     5-123g      5-12    
1    Max     6-745.0d    6-745
2    Bob     5-900.0e    5-90  
3    Ben     2-345       2-34
4    Eva     9-712.x     9-712

The lambda funktion is not working with 3-222 it sclices it to 3-22

I don't get it why it is working for some parts and for others not.

2 Answers2

0

Try this:

df['Action_short'] = df['Action'].str.slice(0, 5)

By using .str on a DataFrame or a single column of a DataFrame (which is a pd.Series), you can access pandas string manipulation methods that are designed to look like the string operations on standard python strings.

sunnytown
  • 1,844
  • 1
  • 6
  • 13
0

# slice by specifying the length you need

df['Action_short']=df['Action'].str[:5]
df
    Person  Action      Action_short
0   Tom     5-123g      5-123
1   Max     6-745.0d    6-745
2   Bob     5-900.0e    5-900
3   Ben     2-345       2-345
4   Eva     9-712.x     9-712
Naveed
  • 11,495
  • 2
  • 14
  • 21