2017-02-09 13 views
5

Tôi có một khung dữ liệu bên dưới.thay chuỗi nếu chiều dài nhỏ hơn x

a = {'Id': ['ants', 'bees', 'cows', 'snakes', 'horses'], '2nd Attempts': [10, 12, 15, 14, 0], 
    '3rd Attempts': [10, 10, 9, 11, 10]} 
a = pd.DataFrame(a) 
print (a) 

Tôi muốn thêm văn bản ('-s') vào bất kỳ thứ gì bằng 4 ký tự. tôi đã thử không thành công dưới đây. vì nó tạo ra lỗi, ValueError: Giá trị thực của một Series là mơ hồ. Sử dụng a.empty, a.bool(), a.item(), a.any() hoặc a.all().

if a['Id'].str.len() == 3: 
    a['Id'] = a['Id'].str.replace('s', '-s') 
else: 
    pass 

Trả lời

5

tôi nghĩ rằng bạn cần loc, nếu cần thay thế cuối cùng s là add cần thiết $:

mask = a['Id'].str.len() == 4 
a.loc[mask, 'Id'] = a.loc[mask, 'Id'].str.replace('s$', '-s') 
print (a) 
    2nd Attempts 3rd Attempts  Id 
0   10   10 ant-s 
1   12   10 bee-s 
2   15    9 cow-s 
3   14   11 snakes 
4    0   10 horses 

Giải pháp với mask:

mask = a['Id'].str.len() == 4 
a.Id = a.Id.mask(mask, a.Id.str.replace('s$', '-s')) 
print (a) 
    2nd Attempts 3rd Attempts  Id 
0   10   10 ant-s 
1   12   10 bee-s 
2   15    9 cow-s 
3   14   11 snakes 
4    0   10 horses 
Các vấn đề liên quan