【问题标题】:How to find the largest number of decimal places in a file?如何找到文件中的最大小数位数?
【发布时间】:2020-11-17 10:02:58
【问题描述】:
【问题讨论】:
标签:
python
pandas
numpy
matplotlib
decimal
【解决方案1】:
假设您感兴趣的列包含 strings,正如您在示例中所展示的,您可以使用 .apply() 函数。
#sample data
df = pd.DataFrame([['4.5'], ['4.61'], ['4.73']], columns=['decimal'])
首先创建一个函数来计算小数,就像你已经做的那样
def count_decimals(input_string):
return abs(decimal.Decimal(input_string).as_tuple().exponent)
然后将此函数应用于您要计算小数的每一列(并将此结果分配给新列)
df.assign(decimal_count=lambda x: x['decimal'].apply(count_decimals))
结果
decimal decimal_count
0 4.5 1
1 4.61 2
2 4.73 2
【解决方案2】:
你可以这样做
maxDecimalPlaces 变量将使用数据中存在的值的最高小数位进行更新。
data = pd.read_csv("data.csv")
maxDecimalPlaces = 0
for index, row in data.iterrows():
# considering you want to evaluate on a column say col_name
decimalPlaces = abs(decimal.Decimal(row["col_name"]).as_tuple().exponent)
if decimalPlaces > maxDecimalPlaces:
maxDecimalPlaces = decimalPlaces
假设 pd 是 pandas 并保持与问题中提供的相同方法来获取小数位。
如果您想在多列上运行,请在 colnames 上添加另一个循环。