【问题标题】:create new column in pandas based on condition根据条件在熊猫中创建新列
【发布时间】:2020-07-03 00:50:58
【问题描述】:

我有一个这样的列的数据框:

    column_1
0   0.75 / 1 / 1.25 
1   0.25 / 0 / -0.25 / 0
2   0 / -0.25 / 0 / -0.25 / 0
3   0 / -0.25 
4   0.5 / 0.25
5   0.25

每一行由一串连续的数字组成(数字之间移动 0.25, 例如从 0 到 0.25 到 0.5,或从 -1 到 -1.25) 我只需要相同数字不出现 2 次(或更多)的行,例如:0.25 / 0 / 0.25 / 0 / 0.25 / 0 或 0.5 / 0.25 / 0.5 我不需要只有一个数字的行,例如 0.25

我要新建一列,并保留符合条件的列(相同的数字不会出现2次(或更多))

    column_1                     new_column
0   0.75 / 1 / 1.25              0.75 / 1 / 1.25 
1   0.25 / 0 / -0.25 / 0         NaN
2   0 / -0.25 / 0 / -0.25 / 0    NaN
3   0 / -0.25                    0 / -0.25 
4   0.5 / 0.25                   0.5 / 0.25
5   0.25                         NaN

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这是拆分这些字符串并爆炸的一种方法,然后只保留那些 Series.is_uniqueTrue 并且它们有多个元素的:

    l = df.column_1.str.split(' / ')
    m = (l.explode()
          .groupby(level=0, sort=False)
          .apply(lambda x: x.is_unique) 
           & (l.str.len()>1))
    df['new_column'] = df.where(m)
    

    print(df)
    
                        column_1        new_column
    0           0.75 / 1 / 1.25   0.75 / 1 / 1.25 
    1       0.25 / 0 / -0.25 / 0               NaN
    2  0 / -0.25 / 0 / -0.25 / 0               NaN
    3                 0 / -0.25         0 / -0.25 
    4                 0.5 / 0.25        0.5 / 0.25
    5                       0.25               NaN
    

    【讨论】:

    • 它返回一个异常:'''Series' object has no attribute 'explode'"
    【解决方案2】:

    使用splitstrip 创建一个数字列表助手系列。将列表的长度与其对应的set 进行比较,并使用布尔逻辑创建new_column

    s = df['column_1'].apply(lambda x: [x.strip() for x in x.split('/')])
    
    df['new_column'] = df.loc[(s.str.len() == s.apply(set).str.len()) & (s.str.len() != 1), 'column_1']
    

    [出]

                        column_1       new_column
    0            0.75 / 1 / 1.25  0.75 / 1 / 1.25
    1       0.25 / 0 / -0.25 / 0              NaN
    2  0 / -0.25 / 0 / -0.25 / 0              NaN
    3                  0 / -0.25        0 / -0.25
    4                 0.5 / 0.25       0.5 / 0.25
    5                       0.25              NaN
    

    【讨论】:

    • 返回异常:“AttributeError: 'float' object has no attribute 'split'”
    【解决方案3】:

    另一种答案:

    # Import libraries
    import pandas as pd
    import numpy as np
    
    # Create DataFrame
    df = pd.DataFrame({
        'column_1': ['0.75 / 1 / 1.25','0.25 / 0 / -0.25 / 0','0 / -0.25 / 0 / -0.25 / 0',
                     '0 / -0.25', '0.5 / 0.25', 0.25, np.nan, 'NaN'
                    ]
    })
    # To handle np.NaN's using .fillna()
    df['column_1'] = df['column_1'].fillna('0')
    
    # To handle cases where numeric values in column
    df['column_1'] = df['column_1'].astype(str)
    
    # Split string to list and compare
    df['split'] = df['column_1'].apply(lambda x: [i.replace('-','') for i in x.split(' / ')])
    df['new_column'] = df['split'].apply(lambda x: np.nan if len(set(x))==1 else
                                         x if len(set(x))==len(x) 
                                         else np.nan)
    df = df.drop('split', axis=1) # drop column
    

    输出

    print(df)
    
                        column_1       new_column
    0            0.75 / 1 / 1.25  [0.75, 1, 1.25]
    1       0.25 / 0 / -0.25 / 0              NaN
    2  0 / -0.25 / 0 / -0.25 / 0              NaN
    3                  0 / -0.25        [0, 0.25]
    4                 0.5 / 0.25      [0.5, 0.25]
    5                       0.25              NaN
    6                          0              NaN
    7                        NaN              NaN
    

    【讨论】:

    • 返回异常:“AttributeError: 'float' object has no attribute 'split'”
    • 这可能是由于column_1 中的数值所致。我已更新代码以首先将column_1 设置为字符串。
    • 我将列转换为字符串,但返回一个带有 NaN 的新列(所有值都是 NaN)
    • (1) 您能否确认上述答案中的代码是否适用于您?因为它在我的电脑上运行良好。 (2) 不看整个数据集很难诊断问题。我猜column_1 可能混合了不同的数据类型。您能否在column_1 中发布与上述问题中发布的数据样本不同的数据样本? (3) 我使用的是 Pandas 版本:1.0.3;和 Python:3.7.4
    • column_1 包含一些 NaN,这可能是原因?
    猜你喜欢
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 2018-11-06
    • 2022-12-16
    • 2022-08-02
    • 2022-08-09
    相关资源
    最近更新 更多