繁体   English   中英

将 pandas 列与 python 中的数字相乘

[英]multiply pandas column with a number in python

我正在尝试将价格列与整数相乘,但它没有发生。

for index,row in df.iterrows():
    a=row['price']
    row['price'] = a[1:]
    b = row['price'].split(' ')[1]

所以我想乘以 100000,其中价格包含“L”,乘以 10000000,其中价格包含“Cr”。 例如,第一个单元格有 50.0 L,所以 output 应该是 5000000.0 我使用了dtype并且 output 是 dtype dtype('O')

    price   area    type    price per sq feet   Address
0   50.0 L  650      1      7.69                Mankhurd
1   1.15 Cr 650      1      17.69               Chembur
2   95.0 L  642      1      14.80               Bhandup West
3   1.6 Cr  650      2      24.61               Goregaon East
5   88.0 L  570      1      15.44               Borivali East

我将不胜感激。 谢谢哟

IIUC,您可以尝试使用series.str.extractseries.map和乘法:

d = {"L":100000,"Cr":10000000}
pat = '|'.join(d.keys())
mapped = df['price'].str.extract('('+pat+')',expand=False).map(d)
df['price'] = pd.to_numeric(df['price'].str.replace(pat,''),errors='coerce') * mapped

print(df)

        price  area  type  price per sq feet        Address
0   5000000.0   650     1               7.69       Mankhurd
1  11500000.0   650     1              17.69        Chembur
2   9500000.0   642     1              14.80   Bhandup West
3  16000000.0   650     2              24.61  Goregaon East
4   8800000.0   570     1              15.44  Borivali East
def func(element):
    
    num, type = element.split()
    
    if type == 'L' : return float(num) * 10**5
    if type == 'Cr': return float(num) * 10**7
df['price'] = df['price'].apply(func)

一种方法是编写 function 来处理您希望如何处理每个元素,然后在相关列上使用 map function :

def convert_price(price):
    price_value = float(price.split(" ")[0])
    if "L" in price:
        return price_value*100000
    elif "Cr" in price:
        return price_value*10000000
    else:
        return price  # or however else you want to handle it
    
df["price_converted"] = df["price"].map(convert_price)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM