d = {'col1': [1.1, 2.1, "ERR", 0.1], 'col2': [3, 4, 5, 6]}
df = pd.DataFrame(data=d)
print(df)
df["t"] = np.where(df["col1"] == "ERR", "T", "F")
df["test"] = np.where(df["col1"] == "ERR", df["col1"], df["col1"]*1)
df["test"] = np.where(df["col1"] == "ERR", df["col1"], df["col1"]*1.1)
print(df)# works fine
df["test"] = np.where(df["col1"] == "ERR", df["col1"], df["col1"]*1)
# TypeError: can't multiply sequence by non-int of type 'float'
df["test"] = np.where(df["col1"] == "ERR", df["col1"], df["col1"]*1.1)无法理解为什么会发生这种事
发布于 2022-05-16 10:55:46
问题是数字与非数字值混合,可能的解决方案是将输出转换为数字:
s = pd.to_numeric(df["col1"], errors='coerce')
df["test"] = np.where(df["col1"] == "ERR", s, s*1)
df["test"] = np.where(df["col1"] == "ERR", s, s*1.1)
print(df)
col1 col2 t test
0 1.1 3 F 1.21
1 2.1 4 F 2.31
2 ERR 5 T NaN
3 0.1 6 F 0.11
print(s)
0 1.1
1 2.1
2 NaN
3 0.1
Name: col1, dtype: float64发布于 2022-05-16 10:59:31
问题不在于np.where。问题在于:
df["col1"]*1.1列的类型是对象,当您试图用浮点数对其进行乘时。您只能对数字列执行此操作。
发布于 2022-05-16 11:40:08
这个错误是因为运行df["col1"]*1.1将试图将'ERR‘乘以1.1,这是不可能的。在python中,不存在使用1的错误*字符串是一个有效的操作,例如,2*'ABC'给出'ABCABC' (在您的情况下它仍然是不需要的,并且只像您期望的那样在1中工作)。
如果要保持列完整,但要乘以非ERR值,则只能对数值进行切片:
df.loc[df['col1'].ne('ERR'), 'col1'] *= 1.1产出:
col1 col2
0 1.21 3
1 2.31 4
2 ERR 5
3 0.11 6注意:对于标识行的更多通用方法,如果您有一个应该跳过的值列表:
m = ~df['col1'].isin(['ERR', 'INVALID'])或跳过所有非数字值:
m = pd.to_numeric(df['col1'], errors='coerce').notna()然后更新:
df.loc[m, 'col1'] *= 1.1https://stackoverflow.com/questions/72258059
复制相似问题