Python 3.x 根据条件替换DF列中的值

Python 3.x 根据条件替换DF列中的值,python-3.x,jupyter-notebook,Python 3.x,Jupyter Notebook,我是Python新手,所以我提前为这段可能很糟糕的代码道歉。我正在尝试完成一个web抓取项目,目前我有一个带有价格列(当前为字符串)的数据框。我的困境是,我想迭代每一行,如果价格显示为每周(包含pw),那么我想将价格更新为每月;i、 e乘以4。对于已经是每月一次的价格,我不想做任何事情 mydf = pd.DataFrame({"prices":["350pw", "1000pm", "600pw", "1000pm", "1000pm"], "Column2":["H", "E", "L",

我是Python新手,所以我提前为这段可能很糟糕的代码道歉。我正在尝试完成一个web抓取项目,目前我有一个带有价格列(当前为字符串)的数据框。我的困境是,我想迭代每一行,如果价格显示为每周(包含pw),那么我想将价格更新为每月;i、 e乘以4。对于已经是每月一次的价格,我不想做任何事情

mydf = pd.DataFrame({"prices":["350pw", "1000pm", "600pw", "1000pm", "1000pm"], "Column2":["H", "E", "L", "P", "!"]})
由此产生:

    prices Column2
0    350pw       H
1   1000pm       E
2    600pw       L
3   1000pm       P
4   1000pm       !
我能够找到行并提取数字。从那里我转换成int,乘以4,但不能使用int的替换函数

for x in mydf[mydf['prices'].str.contains('pw')]['prices']:
    weekly_price = int(x[0:3])
    monthly_price_int = weekly_price * 4
不知道从这里到哪里去

最终结果将是:

    prices Column2
0   1400pw       H
1   1000pm       E
2   2400pw       L
3   1000pm       P
4   1000pm       !


这更像是一个熊猫问题,但这可能是你应该如何做的:

import pandas as pd

mydf = [your df above]

#define a function to convert from weekly to monthly
def make_monthly(cell):
    if 'pw' in cell:
        weekly_price = int(cell[0:3])
        monthly_price_int = weekly_price * 4
        new_cell = str(monthly_price_int)+'pm' #you need to update the period designation as well
        return new_cell
    else:
        return cell
最后,在必要时修改“价格”行中的值:

mydf['prices'] = mydf['prices'].map(make_monthly)
输出:

   prices   Column2
0   1400pm  H
1   1000pm  E
2   2400pm  L
3   1000pm  P
4   1000pm  !

这更像是一个熊猫问题,但这可能是你应该如何做的:

import pandas as pd

mydf = [your df above]

#define a function to convert from weekly to monthly
def make_monthly(cell):
    if 'pw' in cell:
        weekly_price = int(cell[0:3])
        monthly_price_int = weekly_price * 4
        new_cell = str(monthly_price_int)+'pm' #you need to update the period designation as well
        return new_cell
    else:
        return cell
最后,在必要时修改“价格”行中的值:

mydf['prices'] = mydf['prices'].map(make_monthly)
输出:

   prices   Column2
0   1400pm  H
1   1000pm  E
2   2400pm  L
3   1000pm  P
4   1000pm  !