Home > Blockchain >  Replace the value if isnumeric is equal to False - pandas
Replace the value if isnumeric is equal to False - pandas

Time:10-25

How can I display the actual value of column if the result of the isnumeric = False and fill the NaN based on the SKU

DF

      SKU    SKU2
  SKU_ABC    False
        0    NaN
        0    NaN
        0    NaN
  SKU_ACD    False
        0    NaN
        0    NaN

Expected result

      SKU    SKU2
  SKU_ABC    SKU_ABC
        0    SKU_ABC
        0    SKU_ABC
        0    SKU_ABC
  SKU_ACD    SKU_ACD
        0    SKU_ACD
        0    SKU_ACD

Script (only displayed True/False)

df2['SKU2'] = df2['SKU'].str.isnumeric()

I tried this one

df2['SKU2'] = df[~df2['SKU'].str.isnumeric()]

but I got this error

TypeError: bad operand type for unary ~: 'float'

CodePudding user response:

I use this solution Is there a way in Pandas to use previous row value

with for loop:

df['SKU'] = df['SKU'].fillna('0')
df['SKU2'] = df['SKU'].astype(str).str.isnumeric().fillna(False)
for i in range(len(df)):
    if df.loc[i, 'SKU2']:
        df.loc[i, 'SKU2'] = df.loc[i-1, 'SKU2']
    else:
        df.loc[i, 'SKU2'] = df.loc[i, 'SKU']

as I understand the problem here is the isnumeric so let's try to bypass it with other options
with np.where: df['SKU'].str.contains('SKU')

df['SKU2'] = np.where(df['SKU'].astype(str).fillna('0').str.contains('SKU'),df.SKU, None) 
df['SKU2'] = df['SKU2'].ffill()

if it's always '0':df['SKU']=='0'

df['SKU2'] = np.where(df['SKU'].astype(str).fillna('0')=='0', None,df.SKU)
df['SKU2'] = df['SKU2'].ffill()
  • Related