我有一個 df 你可以通過運行它來獲得它:
import numpy as np
import pandas as pd
from io import StringIO
df = """
contract EndDate option
A00118 99999999 AC
A00118 19831231 SLA
A00118 99999999 TPA
A00118 99999999 F
A00118 99999999 FD
"""
df = pd.read_csv(StringIO(df.strip()), sep='\s ',
dtype={"RB": int, "BeginDate": int, "EndDate": int,'ValIssueDate':int,'Valindex0':int})
df
輸出是:
contract EndDate option
0 A00118 99999999 AC
1 A00118 19831231 SLA
2 A00118 99999999 TPA
3 A00118 99999999 F
4 A00118 99999999 FD
現在我想在不使用 .apply 函式的情況下對每一行應用邏輯,因為它非常慢。
邏輯是,如果選項等于 SLA,則 EndDate 將是其值的最后 4 位。
我試過這樣的事情:
df.loc[df['option']=='SLA']['EndDate']=[4:]
但收到語法錯誤
正確的輸出應該是:
contract EndDate option
0 A00118 99999999 AC
1 A00118 1231 SLA
2 A00118 99999999 TPA
3 A00118 99999999 F
4 A00118 99999999 FD
uj5u.com熱心網友回復:
.loc與感興趣的行和列名的布爾掩碼一起使用。剩下的就是字串操作和型別轉換。
>>> df
contract EndDate option
0 A00118 99999999 AC
1 A00118 19831231 SLA
2 A00118 99999999 TPA
3 A00118 99999999 F
4 A00118 99999999 FD
>>> where = df['option'] == 'SLA', 'EndDate'
>>> df.loc[where] = df.loc[where].astype(str).str[-4:].astype(int)
>>> df
contract EndDate option
0 A00118 99999999 AC
1 A00118 1231 SLA
2 A00118 99999999 TPA
3 A00118 99999999 F
4 A00118 99999999 FD
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/433586.html
