Questions tagged «python»

Python是一种多范式,动态类型的多用途编程语言。它旨在快速学习,理解和使用并强制使用干净统一的语法。请注意,Python 2自2020年1月1日起已不再受支持。不过,对于特定于版本的Python问题,请添加[python-2.7]或[python-3.x]标签。使用Python变体或库(例如Jython,PyPy,Pandas,Numpy)时,请将其包含在标签中。

1
python中集的'Bizarre'排序
当我将Python 3.8.0列表转换为集合时,结果集的排序*以一种很简单的方式高度结构化。如何从伪随机列表中提取此结构? 作为实验的一部分,我正在生成一个随机集合。我很惊讶地看到绘制该集合突然显示出该集合中意外的线性结构。因此,有两件事让我感到困惑-为什么转换为一组结果会导致排序*最终突出了这种结构;在较小程度上,为什么伪随机集完全具有这种“隐藏”结构? 编码: X = [randrange(250) for i in range(30)] print(X) print(set(X)) 例如输出 [238, 202, 245, 94, 111, 106, 148, 164, 154, 113, 128, 10, 196, 141, 69, 38, 106, 8, 40, 53, 160, 87, 85, 13, 38, 147, 204, 50, 162, 91] {128, 8, 10, 141, 13, 147, …
14 python 

3
使用熊猫中的两个地理数据框获取最近的距离
这是我的第一个geodatframe: !pip install geopandas import pandas as pd import geopandas city1 = [{'City':"Buenos Aires","Country":"Argentina","Latitude":-34.58,"Longitude":-58.66}, {'City':"Brasilia","Country":"Brazil","Latitude":-15.78 ,"Longitude":-70.66}, {'City':"Santiago","Country":"Chile ","Latitude":-33.45 ,"Longitude":-70.66 }] city2 = [{'City':"Bogota","Country":"Colombia ","Latitude":4.60 ,"Longitude":-74.08}, {'City':"Caracas","Country":"Venezuela","Latitude":10.48 ,"Longitude":-66.86}] city1df = pd.DataFrame(city1) city2df = pd.DataFrame(city2) gcity1df = geopandas.GeoDataFrame( city1df, geometry=geopandas.points_from_xy(city1df.Longitude, city1df.Latitude)) gcity2df = geopandas.GeoDataFrame( city2df, geometry=geopandas.points_from_xy(city2df.Longitude, city2df.Latitude)) 城市1 City Country Latitude Longitude …

4
计算熊猫数据框中相似值的百分比
我有一个数据框df,有两列:脚本(带文本)和扬声器 Script Speaker aze Speaker 1 art Speaker 2 ghb Speaker 3 jka Speaker 1 tyc Speaker 1 avv Speaker 2 bhj Speaker 1 我有以下列表: L = ['a','b','c'] 使用以下代码, df = (df.set_index('Speaker')['Script'].str.findall('|'.join(L)) .str.join('|') .str.get_dummies() .sum(level=0)) print (df) 我得到这个数据框df2: Speaker a b c Speaker 1 2 1 1 Speaker 2 2 …

2
为什么从包含问号的第一个文件转换而来的html文件在单击目录时无法显示在浏览器上?
请下载文件simple.7z并安装在您的sphinx中以重现我在这里描述的问题,为了重现它,您可以运行: make clean make html 下载并安装在您的狮身人面像以重现问题 中有两篇文章sample/source,内容相同,只是标题不同。 cd sample ls source |grep "for-loop" What does "_" in Python mean in a for-loop.rst What does "_" in Python mean in a for-loop?.rst 一个包含?在其中,另一个不包含?。跑步后发生了奇怪的事情make html。 make html ls build/html|grep "for-loop" What does "_" in Python mean in a for-loop.html What does "_" …

2
numpy.unique为集列表提供错误的输出
我有一个列表, sets1 = [{1},{2},{1}] 当我使用numpy的在列表中找到唯一元素时unique,我得到 np.unique(sets1) Out[18]: array([{1}, {2}, {1}], dtype=object) 可以看出,结果是错误的,就像{1}在输出中重复的一样。 当我通过使相似元素相邻来更改输入的顺序时,不会发生这种情况。 sets2 = [{1},{1},{2}] np.unique(sets2) Out[21]: array([{1}, {2}], dtype=object) 为什么会发生这种情况?还是我做的方式有问题?
14 python  list  numpy  set 

2
推断哪些列是日期时间
我有一个巨大的数据框,其中包含许多列,其中许多列都是type的datetime.datetime。问题在于,许多还具有混合类型,包括例如datetime.datetime值和None值(以及可能的其他无效值): 0 2017-07-06 00:00:00 1 2018-02-27 21:30:05 2 2017-04-12 00:00:00 3 2017-05-21 22:05:00 4 2018-01-22 00:00:00 ... 352867 2019-10-04 00:00:00 352868 None 352869 some_string Name: colx, Length: 352872, dtype: object 因此导致object类型列。可以用解决df.colx.fillna(pd.NaT)。问题在于数据框太大,无法搜索单个列。 另一种方法是使用pd.to_datetime(col, errors='coerce'),但是这将强制转换为datetime包含数值的许多列。 我也可以做df.fillna(float('nan'), inplace=True),尽管包含日期的列仍然是object类型,并且仍然会有相同的问题。 我可以采用什么方法将那些其值确实包含datetime值但也可能包含None,以及可能包含一些无效值的列转换为日期时间(提及,因为否则pd.to_datetime在try/ except子句中可以执行)?像是弹性版本pd.to_datetime(col)
14 python  pandas 

3
有没有一种方法可以在2个字段上创建唯一的ID?
这是我的模型: class GroupedModels(models.Model): other_model_one = models.ForeignKey('app.other_model') other_model_two = models.ForeignKey('app.other_model') 本质上,我想要的是other_model在此表中唯一。这意味着,如果存在other_model_oneid 为的记录,则123不应允许创建other_model_twoID为as的另一条记录123。我可以覆盖clean我的猜测,但是我想知道django是否内置了某些东西。 我在PSQL中使用版本2.2.5。 编辑:这不是一个不合时宜的情况。如果我用other_model_one_id=1和其他添加一条记录other_model_two_id=2,我应该不能用other_model_one_id=2和其他添加另一条记录。other_model_two_id=1

2
如何使用pydicom创建JPEG压缩的DICOM数据集?
我正在尝试使用pydicom创建JPEG压缩的DICOM图像。可以在此处找到有关彩色DICOM图像的不错的原始资料,但这主要是理论和C ++。在下面的代码示例中,我在内部创建了一个淡蓝色的省略号output-raw.dcm(未压缩),如下所示: import io from PIL import Image, ImageDraw from pydicom.dataset import Dataset from pydicom.uid import generate_uid, JPEGExtended from pydicom._storage_sopclass_uids import SecondaryCaptureImageStorage WIDTH = 100 HEIGHT = 100 def ensure_even(stream): # Very important for some viewers if len(stream) % 2: return stream + b"\x00" return stream def bob_ross_magic(): image = …

5
在Catalina,Python / Python3,pip / pip3,PATH,zshrc等中使用zsh时出现问题
我最近更新为Catalina和默认的zsh。我可能在过渡期间弄乱了路径,目前我正在尝试整理Python3.7,pip3,命令行PATH和我的zshrc文件的位置。 似乎在/ usr / bin,/ usr / local / bin,/ usr / local / Cellar / python和/Users/[user]/.local/bin中包含潜在的冗余文件 以下是命令的复制品: $ which python3 /usr/bin/python3 $ which python /usr/bin/python $ which pip pip not found $ which pip3 /usr/bin/pip3 $ pip3 -V Traceback (most recent call last): File "/Library/Developer/CommandLineTools/usr/bin/pip3", line 10, in <module> …

5
检查一个numpy数组的所有边界是否都为0 [关闭]
已关闭。这个问题需要更加集中。它当前不接受答案。 想改善这个问题吗?更新问题,使其仅通过编辑此帖子来关注一个问题。 14天前关闭。 检查多维numpy数组的所有面是否都为0的最快方法是什么? 因此,对于一个简单的2D示例,我有: x = np.random.rand(5, 5) assert np.sum(x[0:, 0]) == 0 assert np.sum(x[0, 0:]) == 0 assert np.sum(x[0:, -1]) == 0 assert np.sum(x[-1, 0:]) == 0 虽然这对于正确的2D案例来说是可以的,但是为更大的尺寸编写代码有点乏味,我想知道是否可以使用一些聪明的numpy技巧来使它高效且可维护。
13 python  numpy 

3
无法加载动态库“ libnvinfer.so.6”
我正在尝试正常导入TensorFlow python软件包,但出现以下错误: 这是上面终端图像中的文本: 2020-02-23 19:01:06.163940: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer.so.6'; dlerror: libnvinfer.so.6: cannot open shared object file: No such file or directory 2020-02-23 19:01:06.164019: W tensorflow/stream_executor/platform/default/dso_loader.cc:55] Could not load dynamic library 'libnvinfer_plugin.so.6'; dlerror: libnvinfer_plugin.so.6: cannot open shared object file: No such file or directory 2020-02-23 19:01:06.164030: W …

2
aws cli:找不到哈希md5的ERROR:root:code
尝试运行AWS CLI时,出现此错误: aws ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback …

3
为什么用[:]与iloc [:]分配在熊猫中会产生不同的结果?
我对iloc在熊猫中使用不同的索引方法感到困惑。 假设我正在尝试将1维数据帧转换为2维数据帧。首先,我有以下一维数据框 a_array = [1,2,3,4,5,6,7,8] a_df = pd.DataFrame(a_array).T 我将其转换为大小为的二维数据帧2x4。我首先将二维数据帧预设如下: b_df = pd.DataFrame(columns=range(4),index=range(2)) 然后我使用for循环通过以下代码帮助我将a_df(1-d)转换为b_df(2-d) for i in range(2): b_df.iloc[i,:] = a_df.iloc[0,i*4:(i+1)*4] 它只给我以下结果 0 1 2 3 0 1 2 3 4 1 NaN NaN NaN NaN 但是当我改变b_df.iloc[i,:]为b_df.iloc[i][:]。结果是正确的,如下所示,这是我想要的 0 1 2 3 0 1 2 3 4 1 5 6 7 8 …

6
警告:旧的脚本包装程序正在调用pip
警告:旧的脚本包装程序正在调用pip。这将在以后的pip版本中失败。请参阅 https://github.com/pypa/pip/issues/5599,以获取有关解决基本问题的建议。为了避免这个问题,您可以使用-m pip调用Python,而不是直接运行pip。 当我直接pip list在终端上输入内容时,会收到上述警告。到底是什么意思? 我应该一直使用它python3 -m pip list吗?(如果我以这种方式使用它,则会在没有任何警告的情况下出现相同的输出(包列表)) ps:我在ubuntu 18.10上
13 python  pip 

1
为什么在Python中进行子类化会使事情变慢呢?
我是工作在扩展的简单类dict,我意识到键查找和使用pickle都非常缓慢。 我认为这是我班上的一个问题,所以我做了一些琐碎的基准测试: (venv) marco@buzz:~/sources/python-frozendict/test$ python --version Python 3.9.0a0 (venv) marco@buzz:~/sources/python-frozendict/test$ sudo pyperf system tune --affinity 3 [sudo] password for marco: Tune the system configuration to run benchmarks Actions ======= CPU Frequency: Minimum frequency of CPU 3 set to the maximum frequency System state ============ CPU: use 1 logical CPUs: 3 …

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.