我有一个混合数据类型的数据框,我想更改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
答案 0 :(得分:3)
尝试:
Router
现在:
BrowserRouter
是:
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:])
答案 1 :(得分:2)
这是对熊猫的str
访问器进行切片的一种方法,将mod
减2到整数部分,然后使用str.cat
连接回列:
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
答案 2 :(得分:0)
df['Opportunity'] = df.Opportunity.apply(lambda x: x[:-3]+str(int(x[-3:]) - 1) if int(x[-3:]) % 2 != 0 else x)
Opportunity Quantity Member
0 AB122 2 AACC
1 AB122 3 AACC
2 AB120 4 AACC
3 AB120 1 DDEE
答案 3 :(得分:0)
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