【问题标题】:How to change some values of a pandas df如何更改熊猫 df 的某些值
【发布时间】:2021-09-02 15:55:04
【问题描述】:

我使用np.random.randn创建了一个熊猫df

data = np.random.randn(1, 10)

我得到的输出

[[-0.92408284 -2.61254901  0.95036968  0.81644508 -1.523876   -0.42804606
  -0.74240684 -0.7033438  -2.13962066 -0.62947496]]

现在,如果我想将 2/3 的值更改为极大或极小(即 0.95036968 into 95.03-2.13962066 into -213.96),我该怎么办?

在这里,我需要控制要更改的数字 (2/3/4) 和不断变化的界限(例如,+100 到 -300),它们可以随机更改任何数字。

预期输出:

[[-0.92408284 -2.61254901  95.03  0.81644508 -1.523876   -0.42804606
  -0.74240684 -0.7033438  -213.96 -0.62947496]]

【问题讨论】:

  • 对于您的示例,请问您期望的输出是什么?
  • @Corralien 在问题中添加了预期输出。
  • 我不明白你为什么不考虑-2.61254901而不是-2.13962066
  • @Corralien 随机!不是故意的,只是为了举例。只需更改任何 (2/3/4) 数字即可。

标签: python python-3.x pandas random


【解决方案1】:
data = np.random.randn(1, 10)

# indexes to change
# (can be random too: `np.random.choice(np.arange(data.size), size=3)`
inds_to_change = [2, 3, 5]

# range of values to consider for the difference
lower, upper = -300, +100

# sampling some differences
diffs = np.random.choice(np.arange(lower, upper), size=len(inds_to_change))

# changing array values
data[:, inds_to_change] += diffs

对于给定的更改上下限,我们使用np.random.choice 来抽样一些差异以应用。然后我们索引数组并将它们添加到预定义索引的位置(或者也可以是随机的)。


样本运行:

# to see a cleaner output
>>> np.set_printoptions(suppress=True)

>>> data = np.random.randn(1, 10)
>>> data

array([[-0.29,  0.11,  1.25, -1.36,  0.1 , -0.05, -0.36, -1.09, -0.35,
         2.59]])

>>> inds_to_change = [2, 3, 5]
>>> lower, upper = -300, +100

>>> diffs = np.random.choice(np.arange(lower, upper), size=len(inds_to_change))
>>> diffs

array([  94, -294,  -19])

>>> data[:, inds_to_change] += diffs
>>> data

array([[  -0.29,    0.11,   95.25, -295.36,    0.1 ,  -19.05,   -0.36,
          -1.09,   -0.35,    2.59]])

【讨论】:

  • 完美。我质疑当我使用np.random.uniform(10, -10, size=10) 我得到[ 5.75321779 6.36350066 6.3319098 3.91515514 -0.49512863] 并且形状是(5, ) 但是对于np.random.randn 我得到的形状是(1, 5)。是否可以将(1, 5) 转换为(5, )
  • @Opps_0 np.random.randn(5)?但是您也可以将.squeeze() 链接到您的(1, 5) 形状数组以使其形状为(5,)
猜你喜欢
  • 2021-01-10
  • 2021-06-07
  • 2018-09-25
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 2021-11-10
  • 2023-03-11
  • 1970-01-01
相关资源
最近更新 更多