将“不均匀”值更改为特定偶数

2024-10-06 16:24:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个混合数据类型的数据帧,我想改变str单元格的值(每个单元格由两个字母加上三个数字组成),这样不均匀的数字变成偶数,但数字会减少。AB123应该变成AB122,而不改变它前面的字母。你知道吗

下面是一个混合类型的数据帧示例:

df = pd.DataFrame({'Opportunity':['AB122','AB123','AB125', 'AB124'],
           'Quantity': [2, 3, 4, 1],
           'Member': ["AACC", "AACC", "AACC", 'DDEE']})


print (df)
  Opportunity  Quantity Member
0       AB122         2   AACC
1       AB123         3   AACC
2       AB121         4   AACC
3       AB120         1   DDEE

我希望结果是:

print (df2)

  Opportunity  Quantity Member
0       AB122         2   AACC
1       AB122         3   AACC
2       AB120         4   AACC
3       AB120         1   DDEE

Tags: 数据df字母数字quantitymember数据类型print
3条回答

下面是使用pandas的^{}访问器进行的单向切片,将^{}减去2得到整数部分,然后使用^{}连接回列:

d = df.Opportunity.str[-2:].astype(int)
df['Opportunity'] = df.Opportunity.str[:3].str.cat(d.sub(d.mod(2)).astype(str))

    Opportunity  Quantity Member
0       AB122         2   AACC
1       AB122         3   AACC
2       AB120         4   AACC
3       AB120         1   DDEE

输入数据帧:

print(df)

Opportunity  Quantity Member
0       AB122         2   AACC
1       AB123         3   AACC
2       AB121         4   AACC
3       AB120         1   DDEE

尝试:

df['Opportunity'] = df['Opportunity'].str[:2] + np.where(df['Opportunity'].str[2:].astype(int) % 2, df['Opportunity'].str[2:].astype(int).sub(1).astype(str), df['Opportunity'].str[2:])

现在:

print(df)

是:

  Member Opportunity  Quantity
0   AACC       AB122         2
1   AACC       AB122         3
2   AACC       AB120         4
3   DDEE       AB120         1
df = pd.DataFrame({'Opportunity':['AB122','AB123','AB125', 'AB124'],
               'Quantity': [2, 3, 4, 1],
               'Member': ["AACC", "AACC", "AACC", 'DDEE']})

even = lambda x: int(x) % 2 == 0
df['Opportunity'] = df['Opportunity'].apply(lambda x: x[:2] + (x[2:] if even(x[2:]) else str(int(x[2:]) -1)))

print(df)

输出:

  Opportunity  Quantity Member
0       AB122         2   AACC
1       AB122         3   AACC
2       AB124         4   AACC
3       AB124         1   DDEE

相关问题 更多 >