在Python中将字符串列的数字除以另一列[已关闭]

ct3nt3jp  于 2023-06-25  发布在  Python
关注(0)|答案(3)|浏览(88)

已关闭,此问题需要更focused。目前不接受答复。
**想改善这个问题吗?**更新问题,使其仅通过editing this post关注一个问题。

10天前关闭。
此帖子于10天前编辑并提交审核,未能重新打开帖子:
原始关闭原因未解决
Improve this question
从字符串列“code_input”的数据集开始,我将(通过Python)只为列“days”划分数字。我会将字符串的其余部分保存在“code_output”列中。
我的数据集示例:
| 代码输入|天数|码输出|
| - -----|- -----|- -----|
| ......这是什么?|......这是什么?|......这是什么?|
| 15.5C + 72HT| 3| 5.16C + 24HT|
| 46C + 28HT +6T| 2| 23C + 14HT + 3T|
| ......这是什么?|......这是什么?|......这是什么?|
谢谢你!

zyfwsgd6

zyfwsgd61#

假设你有一个pandas数据框:

>>> df
       code_input  days
0    15.5C + 72HT     3
1  46C + 28HT +6T     2

你必须遍历每一行。您可以使用re.sub的callable as repl参数:

import re

# Python >= 3.8 for walrus operator
df['code_output'] = [re.sub(r'([\d.]+)', lambda x: str(int(x) if (x := float(x[0]) / row.days) - int(x) == 0 else round(x, 2)), row.code_input)
                         for row in df.itertuples()]

输出:

>>> df
       code_input  days     code_output
0    15.5C + 72HT     3    5.17C + 24HT
1  46C + 28HT +6T     2  23C + 14HT +3T

lambda函数将每个数字除以当前天数,并尝试简化数字:如果可能,向下转换为int,否则返回舍入的float

str(int(x) if (x := float(x[0]) / row.days) - int(x) == 0 else round(x, 2))
5lwkijsr

5lwkijsr2#

我完全不知道你最初的数据结构是什么样子的
但是对于字符串的解析和分割,你可以使用正则表达式从字符串中提取数字,然后用“天”来除它们
在那之后,你只需要“重新连接”你的字符串以得到最终的结果
示例:

import re

def get_number(code_input, days):

    numbers = re.split(r'(\d+)', code_input)
    
    all_number = []
    for num in numbers:
        if num.isdigit():
            all_number.append(str(int(num) // days))
        else:
            all_number.append(num)
    
    code_output = ''.join(all_number)
    return code_output

input_dic = {"code_input": "46C + 28HT + 6T", "days": "2"}

code_output = get_number(input_dic["code_input"], int(input_dic["days"]))
print(code_output)

打印23C + 14HT + 3T

nbysray5

nbysray53#

您可以通过以下方式查找数字:

import re
re.findall(r"[-+]?(?:\d*\.*\d+)", '15.5C + 72HT')
['15.5', '72']

days=3
k=[round(float(x)/days,2) for x in re.findall(r"[-+]?(?:\d*\.*\d+)", '15.5C + 72HT')]
#[5.17, 24.0]   # k is a list where numbers are divided by days

'{0}C + {1}HT'.format(*k) 
'5.17C + 24.0HT'
re.findall(r"[-+]?(?:\d*\.*\d+)",'46C + 28HT +6T')
['46', '28', '+6']

days=2
k=[round(float(x)/days) for x in re.findall(r"[-+]?(?:\d*\.*\d+)", '46C + 28HT +6T')]
#[23, 14, 3]    # k is a list where numbers are divided by days

'{0}C + {1}HT +{2}T'.format(*k)
'23C + 14HT +3T'

相关问题