【问题标题】:multiply pandas column with a number in python将熊猫列与python中的数字相乘
【发布时间】:2020-10-24 10:45:16
【问题描述】:

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

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,所以输出应该是 5000000.0 我使用了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

我将不胜感激。 谢谢哟

【问题讨论】:

    标签: python pandas string numpy dataframe


    【解决方案1】:

    IIUC,你可以试试 series.str.extract 和 series.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
    

    【讨论】:

      【解决方案2】:

      您可以这样做的一种方法是编写一个函数来处理您希望如何处理每个元素,然后在相关列上使用 map 函数:

      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)
      

      【讨论】:

        【解决方案3】:
        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)
        

        【讨论】:

        • 乐于助人!如果您喜欢我的回答,可以点击答案左侧的勾号接受。
        猜你喜欢
        • 2020-04-06
        • 2021-09-20
        • 2012-10-21
        • 2019-10-07
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        • 2018-01-24
        • 1970-01-01
        相关资源
        最近更新 更多