小编dim*_*ies的帖子

使用 apply 函数可以工作,但是使用 .assign() 相同的函数却不能?

我有点卡住了,我有一个可以使用的工作函数.apply(),但是,我似乎无法让它与 一起使用.assign()。我希望它能够与分配一起使用,这样我就可以将多个转换链接在一起。

有人能指出我解决问题的正确方向吗?

这有效

data = {'heading': ['some men', 'some men', 'some women']}

dataframe = pd.DataFrame(data=data)

def add_gender(x):
    if re.search("(womens?)", x.heading, re.IGNORECASE):
        return 'women'
    elif re.search("(mens?)", x.heading, re.IGNORECASE):
        return 'men'
    else:
        return 'unisex'

dataframe['g'] = dataframe.apply(lambda ref: add_gender(ref), axis=1)
Run Code Online (Sandbox Code Playgroud)

这不起作用

dataframe = dataframe.assign(gender = lambda ref: add_gender(ref))
Run Code Online (Sandbox Code Playgroud)

类型错误:预期的字符串或类似字节的对象

这是因为.assign()没有提供轴参数吗?那么也许该函数没有在寻找正确的东西?

阅读文档后,.assign您可以生成一个新列,因此我假设输出与.apply(axis=1)

python dataframe pandas

8
推荐指数
1
解决办法
346
查看次数

MySQL中JSON对象的部分更新

下午好,

当我尝试使用 ON 更新 JSON 对象的一部分时DUPLICATE KEY UPDATE,如何使用键更新特定值?

代码执行成功,但当我只想库存在更新时发生变化时,所有值都会更新。

欢迎任何帮助,我不相信,我理解 MySQL JSON Path 语法,或者 JSON_SET 无法实现我的目标?

INSERT INTO table (name, attributes) VALUES
("Sarah", JSON_OBJECT('profile', "F", "el", "[4, 5, 6]")),
("John",  JSON_OBJECT('profile', "M", "el", "[10]"))
AS t
ON DUPLICATE KEY UPDATE
  attributes = JSON_SET(t.attributes, '$.attributes.el',  '$.attributes.el')
                                                         # ^
                                                         # +--- value being inserted
Run Code Online (Sandbox Code Playgroud)

我还尝试过另一种口味,但没有成功:

attributes = JSON_REPLACE(t.attributes, '$.t.el', "$.t.el")
Run Code Online (Sandbox Code Playgroud)

第三次尝试使用通配符和 json 提取,替换整个 JSON_OBJECT()

attributes = JSON_REPLACE(t.attributes, '$.t[2]', JSON_EXTRACT(t.attributes, "$.stock"))
Run Code Online (Sandbox Code Playgroud)

mysql sql json mysql-json

7
推荐指数
1
解决办法
1095
查看次数

标签 统计

dataframe ×1

json ×1

mysql ×1

mysql-json ×1

pandas ×1

python ×1

sql ×1