繁体   English   中英

Pandas select 行如何根据一列的值然后改变另一列的值

[英]Pandas how to select rows based on one column value and then change another column's value

我有一个 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

output 是:

contract    EndDate option
0   A00118  99999999    AC
1   A00118  19831231    SLA
2   A00118  99999999    TPA
3   A00118  99999999    F
4   A00118  99999999    FD

现在我想在不使用的情况下对每一行应用逻辑。应用 function,因为它非常慢。

逻辑是,如果选项等于 SLA,则 EndDate 将是其值的最后 4 位数字。

我试过这样的事情:

df.loc[df['option']=='SLA']['EndDate']=[4:]

但是收到语法错误

正确的 output 应该是:

contract    EndDate option
0   A00118  99999999    AC
1   A00118  1231        SLA
2   A00118  99999999    TPA
3   A00118  99999999    F
4   A00118  99999999    FD

.loc与 boolean 掩码一起用于感兴趣的行列名称。 rest 是字符串操作和类型转换。

>>> 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM