【问题标题】:How do you add new columns with pandas library?如何使用 pandas 库添加新列?
【发布时间】:2021-12-31 14:14:29
【问题描述】:

这是上一个问题的更新版本

我在处理 csv 文件和 pandas 时遇到了一些问题。我想创建一个新列,它是前一列的乘法。比如 ['price', 'pricex2'] [[2,4],[6,12]] 等等,我该怎么做呢?

我有这段代码没有添加新列,它应该更新当前的,即使它不起作用。

   df = pd.read_csv(csvfile)
   df['Jewerly_name_price'] = df['Jewerly_name_price']*2
   print(df)

另外,我在每个价格的末尾都有一个€,并将值乘以 x2 我需要摆脱它,我已经回答了这个问题,但我不知道如何在添加新列。

price = 2.45€ 
numericalPrice = float(price[:-1]

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案1】:

    如果你有:

    df = pd.DataFrame({'col0':[1,2,3]})
    

    您可以通过以下方式向df 添加新列col1

    df = df.assign(col1 = df.col0*2)
    

    你还可以做更复杂的事情,比如:

    df = pd.DataFrame({'col0':["1€","2€","3€"]})
    df = df.assign(col1 = df.col0.apply(lambda row: f'{int(row[:-1])*2}€'))
    

    apply() 函数和f-strings 已被使用的地方。

    【讨论】:

      【解决方案2】:

      df['Jewerly_name_price']*2 中乘以一列字符串只会将相邻的字符串连接多次。为了摆脱'€'并同时乘以值,您可以执行以下操作:

      import pandas as pd
      df = pd.DataFrame({'price': ['2.45€', '3.00€']})
      
      def mul_price(price: str, mul_val=2):
          price_f = float(price[:-1])
          return f"{price_f * mul_val:.2f}€"
      
      df['pricex2'] = df['price'].apply(mul_price)
      
      #Result:
         price pricex2
      0  2.45€   4.90€
      1  3.00€   6.00€
      

      或者,首先去掉“€”,转换为浮点数,然后相乘:

      def price_to_float(price: str):
          return float(price[:-1])
      
      df['price_float'] = df['price'].apply(price_to_float)
      df['pricex2_float'] = df['price_float'] * 2
      
      #Result:
         price  price_float  pricex2_float
      0  2.45€         2.45            4.9
      1  3.00€         3.00            6.0
      

      【讨论】:

      • 谢谢,很有用!但抱歉我忘了补充,价格值在第二列,我怎么能用你的 df = pd.DataFrame({'price': ['2.45€', '3.00€']}) 来代替我的文件的第二列?显然不包括标题。再次感谢您的帮助
      • 我不确定你的意思。如果您的“第二列”具有特定名称,只需将 price 替换为您的第二列名称即可。您也可以使用df['pricex2'] = df.iloc[:, 1].apply(mul_price),其中df.iloc[:, 1] 选择第二列
      • 这就是我调整您的代码的方式,但它引发了一个关键错误:import pandas as pd csvfile = open("D:\\leomu\\Documents\\Python projects\\Bots\\DropShipper \\WebScrapper\\Shein_data_test_run.csv") df = pd.read_csv(csvfile) def Price_Converter(price: str, multiplyer=2): numericPrice = float(price[:-1]) return f"{numericalPrice * multiplyer:. 2f}€" df['pricex2'] = df['Jewerly_name_price'].apply(Price_Converter)
      • 对不起,我不知道如何缩进文本以使其在评论部分看起来更整洁
      【解决方案3】:

      您可以定义一个函数来计算价格,然后使用pd.apply(),如下所示:

      def multiply_price(row):
          string_price = row['Jewerly_name_price']
          price = float(string_price[:-1])
      
          # Change the express below to the data format of your need.
          # Here we are returning a string that is a double (twice) of the
          # original price with a '€' symbol at the end.
          # But of course, we can simple return a float without a '€'.
          return f'{price * 2}€'
      
      df['Jewerly_name_price'] = df.apply(lambda row: multiply_price(row), axis=1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-08
        • 1970-01-01
        相关资源
        最近更新 更多