T
T
tea4panda2021-10-01 15:39:56
Python
tea4panda, 2021-10-01 15:39:56

How to properly add a new pandas column?

I want to add a new column
I have format data:
17.21 ,
47.75.1,
68.20.2

I want to make a new column in pandas so that if there are more than 4 values ​​in a number, then leave only those. otherwise, the original value.
How to apply this format here:

len('17.21') > 4

data_new2['TYPE_NEW']= np.where(data_new2['TYPE']>

Thank you very much!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmshar, 2021-10-01
@tea4panda

Well, probably not more than 4, but more than 5. After all, you count symbols, not numbers. A dot is also a symbol. If you grind something else, then I think you can correct the script yourself:

import pandas as pd
def f(row):
    if len(row['TYPE'])>4 :
        rt = row['TYPE'][0:5]   
    else:
        rt =  row['TYPE']
    return rt
df=pd.DataFrame({'TYPE':('17.21' ,'47.75.1','68.20.2')})
df['TYPE_NEW'] = df.apply(f, axis=1)

Result:
TYPE TYPE_NEW
0    17.21    17.21
1  47.75.1    47.75
2  68.20.2    68.20

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question