Home > Net >  How to swap the first two characters of each element in a pd Series?
How to swap the first two characters of each element in a pd Series?

Time:12-06

I have a series, A = (3223, NaN, NaN, NaN, NaN, 2323, 3323, 2449, NaN). I want two swap the first 2 characters of each element in the series, so A = (2323, NaN, NaN, NaN, NaN, 3223, 3323, 4249, NaN). How can I do this?

CodePudding user response:

A = [1234, 5678, 9112, 9243]

# Iterate over the elements in the list
for i, x in enumerate(A):
    # Check if the current element is a string
    if isinstance(x, str):
        # Extract the first two characters from the string
        first_two_chars = x[:2]
        # Extract the rest of the string (after the first two characters)
        rest_of_string = x[2:]
        # Reverse the order of the first two characters
        reversed_first_two_chars = first_two_chars[::-1]
        # Concatenate the reversed first two characters with the rest of the string
        new_string = reversed_first_two_chars   rest_of_string
        # Assign the new string to the original element in the list
        A[i] = new_string

# The list A should now contain the swapped elements
print(A)

0    2134
1    6578
2    1912
3    2943

CodePudding user response:

List comprehension is useful here:

[str(x)[:2][::-1] str(x)[2:] if !np.isnan(x) else x for x in A]
  • Related