【问题标题】:numpy/pandas: how to add a new column with values based on a list of indices?numpy/pandas:如何根据索引列表添加具有值的新列?
【发布时间】:2017-11-25 02:18:44
【问题描述】:

例如,我有一长串索引:{1,3,7,9,...}。

我的 numpy / pandas 看起来像这样:

Col1   Col2   
1       99
2       95
3       91
4       97
...
n       86

我想附加一个取值 0 或 1 的附加列,具体取决于是否可以在索引列表中找到最左边的列值(如果是,则为 1)。

如何在不遍历索引列表的情况下做到这一点?我尝试了不同的方法但没有成功。

非常感谢!

附:我确实知道 numpy 会经过一个数组数组,因此每一列将只对应于 numpy 内部数组中的一个索引。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    假设col1col2 在名为df 的Pandas 中DataFrame...

    selected_indices = [1,3,7,9]   
    
    # set index as col1, since that seems to be the point of column1
    df.set_index('col1')
    
    # define col3 value as 0 or 1 based on selected_indices list
    df['col3'] = 0
    df['col3'].loc[selected_indices] = 1
    

    【讨论】:

    • 如果索引与 col1 不同,我不确定这是否可行。
    • 感谢您的及时和有益的回应!
    【解决方案2】:

    设置

    l=[1,3,7,9]
    df = pd.DataFrame({'Col1': {0: 1, 1: 2, 2: 3, 3: 4}, 'Col2': {0: 99, 1: 95, 2: 91, 3: 97}})
    df
    Out[190]: 
       Col1  Col2
    0     1    99
    1     2    95
    2     3    91
    3     4    97
    

    解决方案

    您可以使用 np.in1d 检查 Col1 是否存在于索引列表中,然后将 bool 结果转换为 int。

    df['indicator'] = np.in1d(df.Col1,l).astype(int)
    
    df
    Out[186]: 
       Col1  Col2  indicator
    0     1    99          1
    1     2    95          0
    2     3    91          1
    3     4    97          0
    

    【讨论】:

    • 不是批评只是评论...在这种情况下,这适用于填充 01 的值,但不适用于有条件地填充其他值,例如 apples 和 @ 987654326@ 或 02
    • @MaxPower,没错。我想在这种情况下,我们可以将结果用作布尔索引来设置所需的值。
    猜你喜欢
    • 2013-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    相关资源
    最近更新 更多