«python» 태그된 질문

파이썬은 다 패러다임, 동적 타입, 다용도 프로그래밍 언어입니다. 깨끗하고 균일 한 구문을 빠르게 배우고 이해하며 사용하고 적용 할 수 있도록 설계되었습니다. Python 2는 01-01-2020부터 공식적으로 지원되지 않습니다. 그래도 버전 별 Python 질문의 경우 [python-2.7] 또는 [python-3.x] 태그를 추가하십시오. Python 변형 또는 라이브러리 (예 : Jython, PyPy, Pandas, Numpy)를 사용하는 경우 태그에 포함 시키십시오.

5
키가 특정 문자열을 포함하는 파이썬 사전에서 항목 필터링
저는 파이썬으로 무언가를 개발하는 C 코더입니다. 나는 C에서 다음을 수행하는 방법을 알고 있지만 (따라서 파이썬에 적용된 C와 유사한 논리로) 그것을 수행하는 'Python'방식이 무엇인지 궁금합니다. 사전 d가 있고 항목의 하위 집합에 대해 작업하고 싶습니다. 키 (문자열)에만 특정 하위 문자열이 포함되어 있습니다. 즉, C 로직은 다음과 같습니다. for key in d: if …

4
아무것도 출력하지 않는 Python 로깅
내가 쓰는 파이썬 스크립트에서 로깅 모듈을 사용하여 이벤트를 기록하려고합니다. 로거를 구성하려면 다음 코드가 있습니다. ERROR_FORMAT = "%(levelname)s at %(asctime)s in %(funcName)s in %(filename) at line %(lineno)d: %(message)s" DEBUG_FORMAT = "%(lineno)d in %(filename)s at %(asctime)s: %(message)s" LOG_CONFIG = {'version':1, 'formatters':{'error':{'format':ERROR_FORMAT}, 'debug':{'format':DEBUG_FORMAT}}, 'handlers':{'console':{'class':'logging.StreamHandler', 'formatter':'debug', 'level':logging.DEBUG}, 'file':{'class':'logging.FileHandler', 'filename':'/usr/local/logs/DatabaseUpdate.log', 'formatter':'error', 'level':logging.ERROR}}, 'root':{'handlers':('console', 'file')}} logging.config.dictConfig(LOG_CONFIG) …
97 python  logging 

10
파이썬에서 문자열 슬러지 화
"slug"가 무엇인지 " slugify"문자열을 "slugify"하는 가장 좋은 방법을 찾고 있으며 현재 솔루션은 이 레시피를 기반으로 합니다. 나는 그것을 약간 변경했습니다. s = 'String to slugify' slug = unicodedata.normalize('NFKD', s) slug = slug.encode('ascii', 'ignore').lower() slug = re.sub(r'[^a-z0-9]+', '-', slug).strip('-') slug = re.sub(r'[-]+', '-', slug) 누구든지이 코드에 문제가 있습니까? 잘 작동하지만 내가 …
97 python  slug 

8
파이썬에서 여러 키로 객체를 정렬하는 방법은 무엇입니까?
또는 실제로 여러 키로 사전 목록을 정렬하려면 어떻게해야합니까? 사전 목록이 있습니다. b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0}, {u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0}, {u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0}, {u'TOT_PTS_Misc': u'Kirks, …
97 python 

7
세트가 비어있는 경우 부울 반환
내 함수가 끝날 때 내 세트가 비어 있으면 부울 값을 반환하는 더 깨끗한 방법을 찾기 위해 고군분투하고 있습니다. 두 세트의 교차점을 가져 와서 반환 True하거나 False결과 세트가 비어 있는지 여부를 기반으로합니다. def myfunc(a,b): c = a.intersection(b) #...return boolean here 나의 초기 생각은 return c is not None 그러나 내 통역사에서 …

22
Python을 사용하여 plt.show () 창을 최대화하는 방법
호기심을 위해 아래 코드에서이 작업을 수행하는 방법을 알고 싶습니다. 나는 답을 찾고 있었지만 쓸모가 없습니다. import numpy as np import matplotlib.pyplot as plt data=np.random.exponential(scale=180, size=10000) print ('el valor medio de la distribucion exponencial es: ') print np.average(data) plt.hist(data,bins=len(data)**0.5,normed=True, cumulative=True, facecolor='red', label='datos tamano paqutes acumulativa', alpha=0.5) plt.legend() plt.xlabel('algo') plt.ylabel('algo') plt.grid() plt.show()

3
파이썬에서 numpy.linalg.eig를 사용한 후 고유 값 및 관련 고유 벡터 정렬
numpy.linalg.eig를 사용하여 고유 값 및 고유 벡터 목록을 얻습니다. A = someMatrixArray from numpy.linalg import eig as eigenValuesAndVectors solution = eigenValuesAndVectors(A) eigenValues = solution[0] eigenVectors = solution[1] 정렬 후 연관된 고유 벡터가 무엇인지 아는 방식으로 고유 값 (예 : 가장 낮은 값에서 가장 높은 값으로)을 정렬하고 싶습니다. 파이썬 함수로 그렇게하는 …
97 python  sorting  numpy 

2
"not in"조건에 따라 데이터 프레임에서 행 삭제 [중복]
이 질문에는 이미 답변이 있습니다 . SQL에서와 같이 'in'과 'not in'을 사용하여 Pandas 데이터 프레임을 필터링하는 방법 (9 답변) 휴일 3 개월 전 . 날짜 열의 값이 날짜 목록에있을 때 팬더 데이터 프레임에서 행을 삭제하고 싶습니다. 다음 코드는 작동하지 않습니다. a=['2015-01-01' , '2015-02-01'] df=df[df.datecolumn not in a] 다음과 같은 오류가 …
97 python  pandas 

5
목록의 Python os.path.join ()
내가 할 수있는 >>> os.path.join("c:/","home","foo","bar","some.txt") 'c:/home\\foo\\bar\\some.txt' 하지만 내가 할 때 >>> s = "c:/,home,foo,bar,some.txt".split(",") >>> os.path.join(s) ['c:/', 'home', 'foo', 'bar', 'some.txt'] 내가 여기서 무엇을 놓치고 있습니까?


1
두 개의 서브 플롯이 생성 된 후 x 축을 어떻게 공유합니까?
두 개의 서브 플롯 축을 공유하려고하는데 그림이 생성 된 후 x 축을 공유해야합니다. 예를 들어이 그림을 만듭니다. import numpy as np import matplotlib.pyplot as plt t= np.arange(1000)/100. x = np.sin(2*np.pi*10*t) y = np.cos(2*np.pi*10*t) fig=plt.figure() ax1 = plt.subplot(211) plt.plot(t,x) ax2 = plt.subplot(212) plt.plot(t,y) # some code to share both x axis …

7
Tensorflow 백엔드가있는 Keras가 CPU 또는 GPU를 마음대로 사용하도록 강요받을 수 있습니까?
Tensorflow 백엔드 및 CUDA와 함께 Keras를 설치했습니다. 때때로 요청시 Keras가 CPU를 사용하도록하고 싶습니다. 가상 환경에 별도의 CPU 전용 Tensorflow를 설치하지 않고도 수행 할 수 있습니까? 그렇다면 어떻게? 백엔드가 Theano이면 플래그를 설정할 수 있지만 Keras를 통해 액세스 할 수있는 Tensorflow 플래그에 대해 들어 본 적이 없습니다.

7
pip에서 TypeError 발생 : parse ()가 새 패키지를 설치하려고 할 때 예기치 않은 키워드 인수 'transport_encoding'을 받았습니다.
최신 버전의 Anaconda3를 사용하고 있습니다. 방금 설치했고 일부 패키지를 다운로드하려고합니다. Anaconda Prompt를 사용하고 있습니다. pip를 사용하여 (기존 패키지 업그레이드 포함) 작업을 수행하는 동안 다음과 같은 추적을 얻습니다. Exception: Traceback (most recent call last): File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "C:\Users\csprock\Anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run wb.build(autobuilding=True) …

4
DataFrame의 문자열이지만 dtype은 객체입니다.
왜 Pandas는 내가 객체를 가지고 있다고 말하는데, 선택된 열의 모든 항목은 명시 적 변환 후에도 문자열입니다. 이것은 내 DataFrame입니다. <class 'pandas.core.frame.DataFrame'> Int64Index: 56992 entries, 0 to 56991 Data columns (total 7 columns): id 56992 non-null values attr1 56992 non-null values attr2 56992 non-null values attr3 56992 non-null values attr4 56992 …
96 python  pandas  numpy  types  series 

4
try-except 블록과 함께 파이썬 "with"문 사용
이것은 try-except 블록과 함께 파이썬 "with"문을 사용하는 올바른 방법입니까? : try: with open("file", "r") as f: line = f.readline() except IOError: <whatever> 그렇다면 이전 작업 방식을 고려하십시오. try: f = open("file", "r") line = f.readline() except IOError: <whatever> finally: f.close() 세 줄의 코드를 제거 할 수 있다는 "with"문의 주요 이점이 …

당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.