Python/Numpy一维数组每行合并两个元素的实现问题
Hey there! Let's break down your problem and fix it step by step.
Why You're Getting That AxisError
Your combi variable ends up as a 1D regular numpy array (like array(['A_B', 'C_D'], dtype='<U4')), while your original array is a structured array (each element is a tuple with named fields). When you try np.append(..., axis=1) or np.concatenate(..., axis=1), you're trying to add along axis 1—but your original structured array only has 1 dimension (ndim=1), so axis 1 doesn't exist. Plus, regular arrays and structured arrays can't be directly concatenated along an axis like that.
Solution 1: Create the Target Array (Only group3)
Instead of using a slow loop, use numpy's vectorized string operations which are far more efficient. Here's how:
import numpy as np # Your original structured array arr = np.array([('A', 'B'), ('C', 'D')], dtype=[('group1', '<U4'), ('group2', '<U4')]) # Vectorized string concatenation to generate group3 data group3_values = np.char.add(arr['group1'], np.char.add('_', arr['group2'])) # Build the target structured array target_arr = np.array(group3_values, dtype=[('group3', '<U4')]) print(target_arr) # Output: array([('A_B',), ('C_D',)], dtype=[('group3', '<U4')])
If you prefer to stick with your loop approach (not recommended for large datasets), just convert your combi results into a structured array instead of a regular array:
combi = [] for group in arr: combi.append(group[0] + "_" + group[1]) # Convert list to structured array matching your target target_arr = np.array(combi, dtype=[('group3', '<U4')])
Solution 2: Add group3 to the Original Structured Array
If you want to keep the original group1 and group2 fields alongside the new group3, you can create a new structured dtype and populate it:
# Create a new dtype that includes original fields + group3 new_dtype = arr.dtype.descr + [('group3', '<U4')] # Initialize empty array with the new dtype combined_arr = np.empty(arr.shape, dtype=new_dtype) # Copy original field data combined_arr['group1'] = arr['group1'] combined_arr['group2'] = arr['group2'] # Insert the merged group3 values combined_arr['group3'] = np.char.add(arr['group1'] + '_', arr['group2']) print(combined_arr) # Output: array([('A', 'B', 'A_B'), ('C', 'D', 'C_D')], # dtype=[('group1', '<U4'), ('group2', '<U4'), ('group3', '<U4')])
内容的提问来源于stack exchange,提问作者Lotw

