【问题标题】:Assign value to random rows inside DataFrame为 DataFrame 内的随机行赋值
【发布时间】:2020-07-26 17:54:37
【问题描述】:

假设我有一些数据帧的子集(例如,列 a > 5)。

我想为上述子集的 70% 分配 0(例如),并保留所有其他行。

当前索引不是唯一的。

输入:

|   some_index |   a |   b |
|-------------:|----:|----:|
|            1 |   5 |   2 |
|            2 |   4 |   5 |
|            1 |   7 |   8 |
|            2 |  10 |  11 |

输出:

|   some_index |   a |   b |
|-------------:|----:|----:|
|            1 |   0 |   0 |
|            2 |   4 |   5 |
|            1 |   0 |   0 |
|            2 |  10 |  11 |

我想出了以下解决方案:

import pandas as pd
from random import shuffle

df2 = pd.DataFrame(np.array([[5, 2], [4, 5], [7, 8], [10, 11] ]),
                   columns=['a', 'b'] , index = [1, 2, 1, 2])
df2.index.name = 'some_index'
print (df2)

df2.reset_index(inplace=True) #reseting index to have a unique index
ind = df2['a'] > 4 # some condition
ind_by_cond = [row_number for row_number, bool_value in zip(ind.index, ind) if bool_value]
random.shuffle(ind_by_cond) # shuffling to make choose indexes randomly


ind_by_cond = [row_number for row_number, bool_value in zip(ind.index, ind) if bool_value]
# 0.7 is the 70% of the subset, that I would like to change
upper_limit = int(len(ind_by_cond) * 0.7) 
df2.loc[ind_by_cond[:upper_limit], ['a', 'b']] = 0 
df2.set_index('some_index', inplace=True) #returning original index back

print (df2)

有没有更简单优雅(pythonic)的解决方案

附:问题不同于: Randomly assign values to subset of rows in pandas dataframe

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用pandas 函数尝试类似的操作

    import pandas as pd
    
    df2 = pd.DataFrame(np.array([[5, 2], [4, 5], [7, 8], [10, 11] ]),
                       columns=['a', 'b'] , index = [1, 2, 1, 2])
    df2 = df2.reset_index(drop=True)
    selected = df2.loc[df2['a']>5,:]
    fraction_selected = selected.sample(frac=.7)
    fraction_selected[:] = 0
    df2.update(fraction_selected)
    print(df2)
    

    【讨论】:

    • 它看起来比我的提议更好。它也少了 2 行(5 行而不是 7 行)
    猜你喜欢
    • 2021-04-07
    • 1970-01-01
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多