【问题标题】:return specific values from an array从数组中返回特定值
【发布时间】:2021-12-12 18:36:26
【问题描述】:

我有一个这样的数组

array([['Weather1', 428, '74827'],
       ['weather1', 429, '74828'],
       ['weather1', 409, '74808'],
       ['weather2', 11553, '76568'],
       ['weather2', 11573, '76574'],

我只想根据[0] 中的值将[2] 值返回到一个新数组组中

最终结果:

array([['74827', '74828', '74808'],['76568', '76574']]

有什么想法吗?

【问题讨论】:

标签: arrays python-3.x


【解决方案1】:

是的,您可以这样做:

array = [
        ['Weather1', 428, '74827'],
        ['weather1', 429, '74828'],
        ['weather1', 409, '74808'],
        ['weather2', 11553, '76568'],
        ['weather2', 11573, '76574']
]

read_data = [] # stores Weather1, Weather2 etc. as we read that
final_array = [] # stores final arrays

# stores data for weather1, then clears it out and
# then stores data for weather2, and so on...
sub_array = [] 

# read each item of array
for x in array:

    # e.g. for first row, is Weather1 already read?
    # No, it's not read
    if x[0].lower() not in read_data:

        # when you reach weather 2 and hit this statement,
        # sub_array will have data from weather1. So, if you find
        # sub_array with data, it is time to add it to the final_array
        # and start fresh with the sub_array
        if len(sub_array) > 0:
            final_array.append(sub_array)
            sub_array = [x[2]]
        # if sub_array is empty, just add data to it
        else:
            sub_array.append(x[2])
        
        # make sure that read_data contains the item you read
        read_data.append(x[0].lower())

    # if weather1 has been read already, just add item to sub_array
    else:
        sub_array.append(x[2])

# After you are done reading all the lines, sub_array may have data in it
# if so, add to the final alrray
if len(sub_array) > 0:
    final_array.append(sub_array)

print(final_array)

结果:[['74827', '74828', '74808'], ['76568', '76574']]

假设:您的数据是连续的。这意味着,weather1 数据持续几行,然后 weather2(或非 weather1)持续几行,依此类推。

【讨论】:

  • 贡献:如果数据不连续,您也可以按“天气...”对数据进行排序,然后将所有天气 1、天气 2 等放在一起,这样您就可以定义分离按天气变化指数划分的组数。
  • 为什么我会返回 IndexError:索引 2 超出轴 0 的范围,大小为 2
  • @xavi 你的数据怎么样?您的任何数组都没有像'74827' 这样的最后一个字符串吗?
  • 只需重启内核即可解决问题。谢谢
  • @RichardValenz 你说得很好。如果 x[0] 不是顺序的,只需对数据进行排序。谢谢!
猜你喜欢
  • 2020-12-26
  • 1970-01-01
  • 2020-07-09
  • 2021-07-20
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 2017-10-31
  • 2022-12-16
相关资源
最近更新 更多