Search column, if value is not all digits, then cut&paste value to another column same row python pandas

Viewed 98

Wanted to ask for help on a question that has me twisting. I have a dataframe, three columns. First column is suppose to be all numbers. If letters exist in the column1 (anywhere in the value) then cut&paste value to 'Column3' within the same row. I have figured out how to use .loc to filter column for certain values and successfully applied text in column3 saying "value has letters". But can not place code together with the idea to say ( if column1 value != isdigit then cut&paste value to column3 same row). My current test code searches column1, finds letters in value, then moves value to column3 at bottom of column which I do not want. I would appreciate some insight on how to use .loc and isdigit together, not sure. Thanks for taking the time.

import numpy as np
import pandas as pd
# Create a DataFrame
d = {
    'Column1': ['345634', '3fgh98', '765432', '987ke2', '234654', '09hws4'],
    'Column2': [3, 6, 8, 9, 23, 24,],
    'Column3': ['', '', '', '', '', '',]}

df = pd.DataFrame(d, columns=['Column1', 'Column2', 'Column3'])

test = df['Column1']
for i in test:
    if(str(i).isdigit()):
        continue
    else:
        df.loc[(i), 'Column3'] = i

print(df)

#df.loc[(df.Column1 != str.isdigit), 'Column3'] = str. #test code using .loc and isdigit. Notworking

The code above will pick up the value with letters in Column1 and move them to the bottom of Column3. It at least gets the values now I have to figure .loc out to cut from column1 and paste into column3 same row. Below is a picture of what I would like to have happen.

Before:

Column1   Column2   Column3
345634    3
3fgh98    6
765432    8
987ke2    9
234654    23
09hws4    24


After:(What I would like to have)

Column1   Column2   Column3
345634    3
          6         3fgh98       
765432    8
          9         987ke2
234654    23
          24        09hws4

I appreciate your help.

1 Answers

Use, Series.str.match along with the given regex pattern and optional parameter na=False(to treat NaN values as False) to create a boolean mask that corresponds to the condition where the Column1 values contains all the digits, then use boolean indexing with this mask to update the values in Column1 and Column3 as required:

m = df['Column1'].astype(str).str.match('^\d+$', na=False)
df.loc[~m, 'Column3'] = df['Column1']
df.loc[~m, 'Column1'] = ''

Result:

print(df)

  Column1  Column2 Column3
0  345634        3        
1                6  3fgh98
2  765432        8        
3                9  987ke2
4  234654       23        
5               24  09hws4
Related