如何在Pandas DataFrame中按列自定义小数显示格式?
Solution for Pandas DataFrame Formatting Requirements
Hey there! Let's work through your formatting needs for the Pandas DataFrame. I've put together a straightforward approach that hits all your requirements exactly.
Step 1: Define Custom Formatting Functions
We'll create two separate functions to handle the euro and token columns individually, since their rules are different.
Function for euro Column
def format_euro(value): # Check if the value is an integer (decimal part is .0) if value == int(value): return f"{int(value)}" # Otherwise, format to exactly two decimal places else: return f"{value:.2f}"
Function for token Column
def format_token(value): # If the value is an integer, return as integer string if value == int(value): return f"{int(value)}" # Format to 18 decimal places, then strip trailing zeros and unnecessary decimal point formatted_str = "{0:.18f}".format(value).rstrip('0').rstrip('.') return formatted_str
Step 2: Apply the Functions to Your DataFrame
Once the functions are defined, apply them to the respective columns in your DataFrame:
import pandas as pd # Your original DataFrame df = pd.DataFrame({ 'euro': [200.0, 9997.8], 'token': [65.78947368421053, 2631.0] }) # Apply formatting df['euro'] = df['euro'].apply(format_euro) df['token'] = df['token'].apply(format_token) # View the result print(df)
Step 3: Verify the Output
After running the code, your formatted DataFrame will look like this:
| euro | token |
|---|---|
| 200 | 65.78947368421053 |
| 9997.80 | 2631 |
Breakdown of What Each Function Does
format_euro: Checks if the value is a whole number (decimal part is .0). If yes, it converts it to an integer string to remove the.0suffix. For non-integer values, it forces exactly two decimal places (like turning9997.8into9997.80).format_token: First checks if the value is an integer to return a clean integer string. For non-integers, it formats the number to 18 decimal places, then strips any trailing zeros and the decimal point if it's left at the end—this ensures we only keep up to 18 meaningful decimal digits without unnecessary trailing zeros.
内容的提问来源于stack exchange,提问作者Manuel
相关产品推荐
相关产品推荐

