gpt4 book ai didi

python - 从单元格中删除字符并在 python pandas 中将剩余的 float 除以 2

转载 作者:行者123 更新时间:2023-12-05 05:40:26 25 4
gpt4 key购买 nike

我有一个包含多列的数据框,其中一些单元格包含字符“DL”和一个 float 。其他单元格仅包含 float 。

例如:

<表类="s-表"><头><日> 第 1 列第 2 列<正文>第1行DL10.45.6第2行4.7DL8.8

我想用python去掉字符“DL”,把剩下的 float 除以2,没有字符的单元格保持不变,不除以2。

预期结果:

<表类="s-表"><头><日> 第 1 列第 2 列<正文>第1行5.25.6第2行4.74.4

最佳答案

使用Series.str.extract Series.str.extractall对于 DL 之后的值,除以 2 并将非 DL 值替换为原始 DataFrame:

df1 = df.apply(lambda x: x.str.extract('DL(\d+\.\d+)', expand=False))
df = df1.astype(float).div(2).fillna(df).astype(float)
print (df)
Column1 Column2
row1 5.2 5.6
row2 4.7 4.4

关于python - 从单元格中删除字符并在 python pandas 中将剩余的 float 除以 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72431644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com