【问题标题】:How can i split a column based on a condition in Python pandas如何根据 Python pandas 中的条件拆分列
【发布时间】:2020-10-17 17:27:05
【问题描述】:

我的其中一列包含以下数据-

Numbers
100 K
25.20 K
250 K
33.45 K
250
100
10
5
4
1

在上面的数字列中,我想将数字与 K 乘以 1000,而其他数字不乘以 K,我想保持原样。 如何执行列号的这种条件拆分和乘法

提前致谢。

【问题讨论】:

    标签: python-3.x pandas numpy if-statement jupyter-notebook


    【解决方案1】:

    您可以使用带有布尔掩码的numpy.where() 来识别包含'K' 的行:

    mask = df['Numbers'].str.contains('K')
    
    df['Numbers'] = np.where(mask, df['Numbers'].str.extract(r'([\d\.]+)', expand=False).astype(float)*1000, df['Numbers'])
    

    产量:

      Numbers
    0  100000
    1   25200
    2  250000
    3   33450
    4     250
    5     100
    6      10
    7       5
    8       4
    9       1
    

    【讨论】:

      【解决方案2】:

      这是使用自定义函数的一种方法:

      import re
      def func(s):
          # extract the digits with decimal
          s = float(re.sub('[^0-9\\.]', '', s))*1000
          return s
      
      is_k = df['col'].str.contains('K')
      df.loc[is_k, 'col2'] = df.loc[is_k, 'col'].apply(func)
      
      df['col2'] = df['col2'].combine_first(df['col'])
      
             col    col2
      0    100 K  100000
      1  25.20 K   25200
      2    250 K  250000
      3      250     250
      4      100     100
      5       10      10
      

      样本数据

      s=["100 K", "25.20 K", "250 K", "250", "100","10"]
      df = pd.DataFrame({'col': s})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-16
        • 1970-01-01
        • 1970-01-01
        • 2010-10-31
        • 2016-11-19
        • 2021-07-21
        • 1970-01-01
        相关资源
        最近更新 更多