Kobe Janssens
Kobe Janssens

Reputation: 318

Rounding specific columns in pandas (python)

I'm trying to round the columns binance, binanceAmount, livecoin, livecoinAmount, ..., profit and procent. I import the data from a csv. This are the first 10 rows:

enter image description here This is my code:

decimals = {}
for exchange in usableExchanges:
    decimals[exchange] = 8
    decimals[exchange + "amount"] = 2


df.round(decimals)
df.round({'profit': 1, 'procent': 2})

Upvotes: 0

Views: 389

Answers (1)

jezrael
jezrael

Reputation: 862481

You can assign to dictionary and assign output to DataFrame:

decimals = {'profit': 1, 'procent': 2}
for exchange in usableExchanges:
    decimals[exchange] = 8
    decimals[exchange + "Amount"] = 2

df = df.round(decimals)
print (df)

Sample:

np.random.seed(2019)

cols = ['binance','binanceAmount','kucoin','kucoinAmount','profit','procent']
df = pd.DataFrame(np.random.randint(10, size=(4,6)), columns=cols) / 2.34
print (df)
    binance  binanceAmount    kucoin  kucoinAmount    profit   procent
0  3.418803       0.854701  2.136752      3.418803  2.564103  3.418803
1  0.000000       0.000000  2.991453      3.418803  2.136752  1.282051
2  0.000000       0.854701  2.136752      2.991453  3.418803  2.136752
3  1.709402       0.000000  0.427350      2.564103  0.000000  0.854701

usableExchanges = ['binance','kucoin']

decimals = {'profit': 1, 'procent': 2}
for exchange in usableExchanges:
    decimals[exchange] = 8
    decimals[exchange + "Amount"] = 2

df = df.round(decimals)
print (df)
    binance  binanceAmount    kucoin  kucoinAmount  profit  procent
0  3.418803           0.85  2.136752          3.42     2.6     3.42
1  0.000000           0.00  2.991453          3.42     2.1     1.28
2  0.000000           0.85  2.136752          2.99     3.4     2.14
3  1.709402           0.00  0.427350          2.56     0.0     0.85

Upvotes: 1

Related Questions