条件替换列值mathematica

时间:2014-03-21 05:11:40

标签: replace wolfram-mathematica conditional

我有一个30,000个点的数据集,格式为x,y,z,c,其中x,y,z分别是纬度,长度和高度," c"是数字形式的分类。

完整的数据集有七个分类,1-7,

我需要有条件地更改所有点的第四列数,以便将7个分类合并为4个。

数字1& 2保持不变。 3,4,5将成为3,和 6,7将成为4.

即如果第四列值为2,则保持为2.如果第四列值为5,则需要将其更改为3.

示例:

http://imgur.com/BEaAWTr

两个

StringReplace  
ReplacePart 

看起来它们应该有效,但我不确定如何用相同的输出数替换多个输入?

2 个答案:

答案 0 :(得分:1)

In[1]:= olddata = {
  {1, 2, 3, 1}, {2, 1, 4, 2}, {3, 3, 2, 3}, {4, 3, 2, 4}, {6, 1, 2, 5}, {1, 1, 2, 6},
  {4, 3, 5, 7}, {2, 1, 7, 1}, {3, 4, 4, 2}, {5, 3, 1, 3}, {2, 3, 4, 4}, {1, 1, 3, 5},
  {6, 1, 2, 6}, {5, 3, 5, 7}};

In[2]:= newdata = olddata /. {
  {x_, y_, z_, 4}->{x, y, z, 3}, {x_, y_, z_, 5}->{x, y, z, 3},
  {x_, y_, z_, 6}->{x, y, z, 4}, {x_, y_, z_, 7}->{x, y, z, 4}}

Out[2]= {
  {1, 2, 3, 1}, {2, 1, 4, 2}, {3, 3, 2, 3}, {4, 3, 2, 3}, {6, 1, 2, 3}, {1, 1, 2, 4},
  {4, 3, 5, 4}, {2, 1, 7, 1}, {3, 4, 4, 2}, {5, 3, 1, 3}, {2, 3, 4, 3}, {1, 1, 3, 3},
  {6, 1, 2, 4}, {5, 3, 5, 4}}

答案 1 :(得分:1)

使用比尔的数据

data = {
  {1, 2, 3, 1}, {2, 1, 4, 2}, {3, 3, 2, 3}, {4, 3, 2, 4}, {6, 1, 2, 5}, {1, 1, 2, 6},
  {4, 3, 5, 7}, {2, 1, 7, 1}, {3, 4, 4, 2}, {5, 3, 1, 3}, {2, 3, 4, 4}, {1, 1, 3, 5},
  {6, 1, 2, 6}, {5, 3, 5, 7}};

现在

data[[All, -1]] = If[(z = Quotient[#, 3]) == 0, #, z - 1 + 3] & /@ data[[All, -1]]   

现在数据变为

{{1, 2, 3, 1}, {2, 1, 4, 2}, {3, 3, 2, 3}, {4, 3, 2, 3}, {6, 1, 2, 3}, {1, 1, 2, 4}, 
 {4, 3, 5, 4}, {2, 1, 7, 1}, {3, 4, 4, 2}, {5, 3, 1, 3}, {2, 3, 4, 3}, {1, 1, 3, 3}, 
 {6, 1, 2, 4}, {5, 3, 5, 4}}