【python-将int或float列转换为百分比分布】教程文章相关的互联网学习教程文章

python – format()int as float【代码】

我想知道它是否有办法做我想要的. 使用格式字符串内置方法,可以将float打印为int:some_float = 1234.5678 print '%02d' % some_float # 1234通过扩展类string.Formatter也可以做到这一点:class MyFormatter(Formatter):def format_field(self, value, format_spec):if format_spec == 't': # Truncate and render as intreturn str(int(value))return super(MyFormatter, self).format_field(value, format_spec)MyFormatter()...

python – 将float64列转换为datetime pandas【代码】

我有以下pandas DataFrame列dfA [‘TradeDate’]:0 20100329.0 1 20100328.0 2 20100329.0 ...我希望将它转换为日期时间. 基于SO上的另一个步骤,我首先将其转换为字符串,然后应用strptime函数.dfA['TradeDate'] = datetime.datetime.strptime( dfA['TradeDate'].astype('int').to_string() ,'%Y%m%d')但是,这会返回我的格式不正确的错误(ValueError). 我发现的一个问题是列不是正确的字符串,而是对象. 当我尝试:dfA[...

根据字符串在python中的性质从字符串转换为float或整数【代码】

参见英文答案 > Convert a list of strings to either int or float 6个解析文件后,我获得了一个包含数值的字符串列表,比方说:my_list = ['1', '-2.356', '00.57', '0', '-1', '02678', '0.005367', '0', '1']为了获得这些数值,我执行以下操作:new_list = [float(i) for i in my_list] . 问题是整数值 – 我处理的文件中的大多数 – 也被转换为float,因此占用更多的内存 – 更不用说其他问题...

改变Float的精度并在Python中存储【代码】

我一直在寻找答案,只发现了我的问题.我通过这个过程来评论代码,说明哪些有效,哪些无效我为每一行得到了什么错误.提前致谢.## list_of_numbers is a list with numbers# like '3.543345354'## I want to change to a number with two places ### for each item in the listfor idx, value in enumerate(list_of_numbers):# make sure it is not none if value != None: ## convert to a float - this workstemp_val = float(value)#...

python – 为什么这行告诉我一个float不能用作整数【代码】

我有这一行,我的脚本被抓住了:for d in range(len(r)/2)我不确定它在浮点数中的价值是多少.我尝试将r / 2的长度转换为int,但仍然会出现此错误.我是Python新手,真的输了.解决方法:在Python 3.x中,/ division运算符总是给出一个浮点值.要使用整数除法,请使用//:for d in range(len(r) // 2):我怀疑你尝试了范围(int(len(r))/ 2),但这不会改变除法的工作方式.

python – 为什么Django DecimalField允许我存储Float或字符串?【代码】

我不明白Django DecimalField的行为. 它被定义为:A fixed-precision decimal number, represented in Python by a Decimal instance.但是,使用以下模型:class Article(models.Model)unit_price = DecimalField(max_digits=9, decimal_places=2)我可以用至少3种方式创建一篇文章:article = Article.objects.create(unit_price="2.3") type(article.unit_price) >>> strarticle = Article.objects.create(unit_price=2.3) type(ar...

python:将2维字符串列表转换为float【代码】

我有一个2维类型字符串列表我试图将其转换为int.到目前为止我尝试过的事情:[[float(i) for i in lst[j] for j in lst]使用for循环:for i in range(len(lst)):for j in range(len(lst[i])):lst[i][j]=float(lst[i][j])解决方法: >>> nums = [['4.58416458379', '3.40522046551', '1.68991195077'], ['3.61503670628', '5.64553650642', '1.39648965337'], ['8.02595866276', '8.42455003038', '7.93340754534']] >>> [[float(y) f...

扩展python内置类:float【代码】

我想改变float.__str__ float类型的构建函数(python 2) 我试图扩展这个类.class SuperFloat(float):def __str__(self):return 'I am' + self.__repr__()但是,当我添加它时,它变成了正常的浮动egg = SuperFloat(5) type(egg+egg)返回浮动 我的最终目标也是egg += 5保持超级浮动解决方法:您需要覆盖类型上的“魔术方法”:__ add__,_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ...

python – pandas如何将所有字符串值转换为float【代码】

我想将Pandas DataFrame中的所有字符串值转换为float,我可以定义一个短函数来执行此操作,但它不是Pythonic方法.我的DataFrame看起来像这样:>>> df = pd.DataFrame(np.array([['1', '2', '3'], ['4', '5', '6']])) >>> df0 1 2 0 1 2 3 1 4 5 6 >>> df.dtypes 0 object 1 object 2 object dtype: object >>> type(df[0][0]) <type 'str'>我只是想知道是否有一些Pandas DataFrame的内置函数将所有字符串值转换为fl...

python – 构建条形图时不支持的操作数类型 – :’str’和’float’【代码】

以前,我问过get week numbers on multiple year that is ready for plotting,根据jezrael的回答,我做了这个:sheet2['device_create_week'] = sheet2['device_create_at'].dt.strftime('%Y-%V') sheet2.groupby(['device_create_week']).size().reset_index(na??me='device created count weekly')然后,我转向绘图import matplotlib.pyplot as plt from matplotlib import rcParams rcParams['figure.figsize'] = (10, 6) rcParams...

Python float和int行为【代码】

当我尝试检查浮点变量是否包含完全整数值时,我得到了下面的奇怪行为.我的代码:x = 1.7 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) print "----------------------"x = **2.7** print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x)) x += 0.1 print x, (x == int(x))我得到了下面的奇怪输出...

python – 添加到numpy.nextafter()float会返回意外的结果【代码】

根据Wolfram Alpha的说法,这对于x> 1来说是正确的. 2.6.0/(x+16) > 2.0/(x+4)为了获得尽可能小的x,我正在使用numpy.nextafter().>>> from numpy import nextafter >>> x = nextafter(2,2+1) >>> x 2.0000000000000004然而.>>> 6.0/(x+16) > 2.0/(x+4) False奇怪的.>>> x+1 3.0000000000000004 >>> x+4 6.0那么如何获得实际可能的最小x> 2对于这种情况?解决方法: import numpy as npx = 2.0 while True:if 6.0/(x+16) > 2.0/(x+4):...

python – 需要将字符串读入float数组【代码】

我有一个如下文本文件.我想将给定值读作浮点列表.之后我会做一些计算.我使用split函数和convertion来浮动.但我无法转换第一个和最后一个,因为这两个方括号. ([]).它给出了如下错误. 文件格式[-1.504, 1.521, 1.531, 1.1579, -2.2976, 2.5927,... 1000 records] [2.758, -0.951, -1.7952, 0.4255, 2.5403, 1.0233,... 1000 records] [0.682, -2.205, 2.1981, 2.1329, 0.1574, -0.4695,... 1000 records]错误Traceback (most recent ...

python – TypeError:不能将序列乘以’float’3.3类型的非int【代码】

好吧,我已经编写了代码,希望它可以工作但我得到TypeError:不能将序列乘以’float’类型的非int. 这是我拥有的代码:uTemp = input("Enter Temperature Variable: ")cOrF = input("Do you want C for celcius, or F for Farehnheit?: ")if cOrF:F = 1.8 * uTemp + 32解决方法:该错误告诉您不能将uTemp(一个字符串)乘以浮点数(1.8).这很有道理,对吗?什么是八分之一弦?将uTemp转换为float:uTemp = float(input("Enter Temperature...

TypeError:’float’对象不可迭代,Python列表【代码】

我正在用Python编写程序,并试图扩展一个列表:spectrum_mass[second] = [1.0, 2.0, 3.0] spectrum_intensity[second] = [4.0, 5.0, 6.0] spectrum_mass[first] = [1.0, 34.0, 35.0] spectrum_intensity[second] = [7.0, 8.0, 9.0]for i in spectrum_mass[second]:if i not in spectrum_mass[first]:spectrum_intensity[first].extend(spectrum_intensity[second][spectrum_mass[second].index(i)])spectrum_mass[first].extend(i)但...