【问题标题】:Python: Replacing every number in an array with a different numberPython:用不同的数字替换数组中的每个数字
【发布时间】:2016-03-09 14:52:38
【问题描述】:

我有以下格式的数据(在 ASCII 文件中):

363 28 24 94

536 28 24 95

我们有速度、时间、纬度、经度。 时间、纬度和经度值都是真实值的代码。例如,时间 28 对应于 2015 年 2 月 1 日,纬度 24 对应于真实纬度 -67 等。

有许多不同的编码值。时间范围为 0-28,纬度为 0-24,经度为 0-108。

我希望将每一个“代码”值替换为其真正的对应值并输出到文本文件中。 文本文件的格式是速度、真时间、真纬度、真长。

我尝试过使用字典和替换来做到这一点,但是替换似乎不喜欢我在数组中读取的事实。

我还应该提到,上面显示的原始格式的输入文件有 79025 行长,每行我必须替换 3 个值。

这是我当前的尝试,但无法处理错误消息:AttributeError: 'numpy.ndarray' object has no attribute 'replace'

data=np.genfromtxt('./data/u_edit_2.coords')
time=data[:,[1]]
lat=data[:,[2]]
lon=data[:,[3]]
def replace_all(text, dic):
     for i, j in dic.iteritems():
         text = text.replace(i, j)
     return text
reps = {'0':'2015-01-02', '1':'23773', '2':'23774'}
time_new = replace_all(time, reps)
print time_new

任何建议都将不胜感激,干杯。

【问题讨论】:

  • 如果代码通过简单的函数转换为实际值,那将是一种更有效的转换方式。代码与值有什么关系?

标签: python arrays numpy replace


【解决方案1】:

这看起来作为文件处理问题处理得更好。然后,您可以处理文件一次,并在需要时读取处理后的数据,无需额外处理。

fmt = "{},{},{},{}\n"  #or whatever format you want
def transform(line):
  speed, time, lat, lon = line.strip().split()
  return fmt.format(
    speed,
    true_time(time),
    true_lat(lat),
    true_lon(lon)
  )

#change the next three functions to fit your needs
def true_time(time):
  return time
def true_lat(lat):
  return lat
def true_lon(lon):
  return lon

fin = open("c:/temp/temp.txt","r")
fout = open("c:/temp/temp2.txt","w")
for line in fin:
  if line.strip(): #ignore empty lines
    fout.write(transform(line))

fin.close()
fout.close()

【讨论】:

    【解决方案2】:

    您的代码看起来像索引,因此您可以使用一些 numpy 索引技巧来获得结果:

    # your values go here, where lat_values[24] = -67, etc.
    time_values = np.array(['2015-01-01', '2015-01-02', ...])
    lat_values = np.array([...])
    lon_values = np.array([...])
    
    # read the coded coords
    _, time, lat, lon = np.loadtxt('coords', dtype=int).T
    
    # decode
    time = time_values[time]
    lat = lat_values[lat]
    lon = lon_values[lon]
    

    【讨论】:

      猜你喜欢
      • 2020-10-19
      • 1970-01-01
      • 2021-05-18
      • 2020-09-26
      • 2023-02-17
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多