3 回答

TA貢獻1777條經驗 獲得超3個贊
else
缺少該語句,因此apply
不知道如果條件失敗該怎么辦。通過else x
在if
條件后添加,它將起作用。
apply(lambda x:x[0:-1] + x[-1].upper() if(x.startswith('abc') & x.endswith('n')) else x)

TA貢獻2012條經驗 獲得超12個贊
這將大寫最后一個字符(before n)并將其余字符小寫:
s = 'abcdirtybitn'
print(s[:-2].lower() + s[-2:].capitalize() if s.startswith('abc') and s.endswith('n') else s)
輸出:
abcdirtybiTn
如果您希望最后一個字符n大寫:
print(s[:-1].lower() + s[-1:].capitalize() if s.startswith('abc') and s.endswith('n') else s) # abcdirtybitN
編輯:
如果您不想操作/小寫所有其他內容:
s = 'abcDirtyBitn'
print(s[:-1] + s[-1:].capitalize() if s.startswith('abc') and s.endswith('n') else s)
輸出:
abcDirtyBitN
和:
s = 'abcDirtyBitn'
print(s[:-2] + s[-2:].capitalize() if s.startswith('abc') and s.endswith('n') else s)
輸出:
abcDirtyBiTn

TA貢獻1825條經驗 獲得超6個贊
我認為這可能是一種有效的解決方案:
In [47]: l
Out[47]: ['abcdfn', 'abc', 'abcn', 'Acv', 'Abc']
In [48]: df = pd.DataFrame(l)
In [49]: df
Out[49]:
0
0 abcdfn
1 abc
2 abcn
3 Acv
4 Abc
In [50]: mask = df[0].str.startswith('abc') & df[0].str.endswith('n')
In [51]: df.loc[mask, 0] = df[mask][0].apply(lambda x : x[0:-1] + x[-1].upper())
In [52]: df
Out[52]:
0
0 abcdfN
1 abc
2 abcN
3 Acv
4 Abc
添加回答
舉報