user90664
user90664

Reputation: 75

How can I round each number in each array in specific columns of a pandas dataframe?

I have a pandas dataframe that looks like this:

FileName    Num     A                           B                 
FileName1   3       [19.19047, ..., 1023.29384] [188.49382, ..., 1252.94759] 
FileName2   5       [52.39672, ..., 2104.93745] [472.94733, ..., 2457.84753] 
FileName3   4       [18.02747, ..., 1532.84729] [356.99482, ..., 2018.34852] 

How can I round each number in the arrays in columns A and B to two decimal places?

If I extract column A or B into its own dataframe, I can use [([round(j) for j in i]) for i in A], but I would like to avoid having to extract anything.

Upvotes: 0

Views: 894

Answers (2)

NYC Coder
NYC Coder

Reputation: 7594

Try this:

df[['A', 'B']] = df[['A', 'B']].apply(lambda x: [np.round(i, 2) for i in x ])
print(df)

    FileName                 A                  B
0  FileName1  [19.19, 1023.29]  [188.49, 1252.95]

Upvotes: 1

null
null

Reputation: 2137

You can simply use np.round to round the whole array at a time.

Try this,

df['A'] = df['A'].apply(lambda x: np.round(x, 2))
df['B'] = df['B'].apply(lambda x: np.round(x, 2))

Upvotes: 1

Related Questions