在熊猫中舍入特定列(Python)

时间:2019-02-10 16:27:31

标签: python pandas

我正在尝试对binance,binanceAmount,livecoin,livecoinAmount,...,利润和procent进行四舍五入。我从csv导入数据。这是前10行:

enter image description here 这是我的代码:

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


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

1 个答案:

答案 0 :(得分:1)

您可以分配给字典并将输出分配给DataFrame

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

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

示例

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
相关问题