简体   繁体   中英

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.

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))

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM