lambda功能带有循环和条件

发布于 2025-02-07 21:34:43 字数 498 浏览 1 评论 0原文

我想在所有行中处理PANDAS DataFrame的列。

示例:

df_column:
    0     urewjf, abc, urewurwe
    1     fdsfs, kjf, oirpiewpoirew...
    2     ab, yryrewy, popof...

我想处理的值:

  • 在具有Len< 4示例的字符串开头添加空白:'abc','ab'

我试图将每个行/系列转换为字符串,然后运行lambda函数将其应用于每一行:

list(map(lambda x: (x.rjust(5) for x in df.column if len(x) < 4), df.column))

它不起作用。

另外,由于系列类型,我使用.apply()时会遇到问题,但是显然我的lambda功能未正确构建。

有什么想法吗? 先感谢您

I have a column in Pandas DataFrame which I would like to process for all rows.

Example:

df_column:
    0     urewjf, abc, urewurwe
    1     fdsfs, kjf, oirpiewpoirew...
    2     ab, yryrewy, popof...

What I want to do with thouse values:

  • add blank space in the beginning of the strings which have len<4 EXAMPLE: ' abc', ' ab'

I was trying to convert each row/Series into string and then run lambda function to apply it for each row:

list(map(lambda x: (x.rjust(5) for x in df.column if len(x) < 4), df.column))

It was not working.

Also, I have issues when I use .apply() because of the Series type, but apparantly my lambda function is not constructed correctly.

Any ideas?
Thank you in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还在原地等你 2025-02-14 21:34:43

您可以只使用Pandas矢量化的字符串方法:

df.<your_column_name> = df.<your_column_name>.str.rjust(5)

You can just use a pandas vectorised string methods:

df.<your_column_name> = df.<your_column_name>.str.rjust(5)
情丝乱 2025-02-14 21:34:43
df = pd.DataFrame({
    "TX_F1": [
        "urewjf",
        "fdsfs",
    ],
    "TX_F2": [
        "abc",
        "kjf"
    ]
})

df.applymap(lambda x: str(x).rjust(5))
df = pd.DataFrame({
    "TX_F1": [
        "urewjf",
        "fdsfs",
    ],
    "TX_F2": [
        "abc",
        "kjf"
    ]
})

df.applymap(lambda x: str(x).rjust(5))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文