2017-02-09 27 views
5

'dan daha az ise string'i değiştirin. Aşağıda bir veri tablom var.eğer uzunluk 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) 

4 karaktere eşit olan herhangi bir şeye metin ('-s') ekleyebilmek istiyorum. Ben aşağıda başarısız çalıştı. Hata üretirken, ValueError: Bir Serinin gerçek değeri belirsizdir. A.empty, a.bool(), a.item(), a.any() veya a.all() kullanın.

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

cevap

5

Geçen yerine gerekirse, loc gerek s olan gerekli eklenti $:

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 

Çözüm mask ile:

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