【问题标题】:Any function in numpy/pandas/python to search and replacenumpy/pandas/python 中的任何函数来搜索和替换
【发布时间】:2015-07-16 00:52:03
【问题描述】:

我有这样的 4x4 矩阵 ds1=

4  13  6  9 
7  12  5  7
7  0  4  22  
9  8  12  0

和其他包含两列的文件: ds2 =

4  1
5  3
6  1
7  2
8  2
9  3
12  1
13  2
22  3

ds1 = ds1.apply(lambda x: ds2_mean[1] if [condition])

要添加什么条件来比较和检查 ds1 和 ds2 中的元素是否相等?

我希望将第二个矩阵中的 col1 值替换为矩阵 1 中的 col2 值,因此结果矩阵应如下所示

1  2  1  3
2  1  3  2
2  0  1  3
3  2  1  0

请参阅Replacing mean value from one dataset to another 这不能回答我的问题

【问题讨论】:

  • 请发布您的代码、您尝试过的内容、遇到的错误等。还要说明您链接的答案的原因和部分对您不起作用,并澄清您的问题少量。此外,语法,大写,标点符号。 ;)
  • @Will:我更新了,如果你有任何建议,我很感激

标签: python numpy matrix pandas


【解决方案1】:

如果您正在使用 numpy arrays,您可以这样做 -

# Make a copy of ds1 to initialize output array 
out = ds1.copy()

# Find out the row indices in ds2 that have intersecting elements between 
# its first column and ds1
_,C = np.where(ds1.ravel()[:,None] == ds2[:,0])

# New values taken from the second column of ds2 to be put in output
newvals = ds2[C,1]

# Valid positions in output array to be changed
valid = np.in1d(ds1.ravel(),ds2[:,0])

# Finally make the changes to get desired output
out.ravel()[valid] = newvals

样本输入、输出-

In [79]: ds1
Out[79]: 
array([[ 4, 13,  6,  9],
       [ 7, 12,  5,  7],
       [ 7,  0,  4, 22],
       [ 9,  8, 12,  0]])

In [80]: ds2
Out[80]: 
array([[ 4,  1],
       [ 5,  3],
       [ 6,  1],
       [ 7,  2],
       [ 8,  2],
       [ 9,  3],
       [12,  1],
       [13,  2],
       [22,  3]])

In [81]: out
Out[81]: 
array([[1, 2, 1, 3],
       [2, 1, 3, 2],
       [2, 0, 1, 3],
       [3, 2, 1, 0]])

【讨论】:

  • 非常感谢,您能再帮忙做一件事吗?获取矩阵元素中邻居的平均值,如果邻居元素是na,则跳过该邻居
  • 这是 3x3 的 mcode,但对于像 1kx1k 这样的大矩阵,这是不可行的:` def neighbors(i,j,a): return [a[i][j-1], a [i][(j+1)%len(a[0])], a[i-1][j], a[(i+1)%len(a)][j]] [[np.平均值(邻居(i,j,a))对于范围内的j(len(a [0]))]对于范围内的i(len(a))]`
  • @bigdata 这听起来像是一个完全不同的问题需要解决。你能把它作为一个新问题发布吗?
  • @Divakar:谢谢,但我在这里得到'DataFrame' object has no attribute 'ravel'
  • @Aamirkhan 您需要将其转换为 numpy 数组,因为顶部的解决方案状态。可能 np.array(ds1) 等可能会起作用
【解决方案2】:

这是另一种解决方案。使用 DataFrame.replace() 函数。

df1.replace(to_replace= df2[0].tolist(), value= df2[1].tolist, inplace=True)

【讨论】:

    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2020-01-21
    • 1970-01-01
    • 2021-05-02
    • 2018-08-11
    • 2014-06-16
    相关资源
    最近更新 更多