我有以下清单:
mylist=[[3, 95],[8, 92],[18, 25],[75, 78],[71, 84],-9999,[96, 50],[91, 70],-9999,[19, 60]]
在其中,除了作为-9999值的值之外,每个元素本身就是一个列表int。
假设我想使用for循环将每个元素转换为 a string,以便将其写入一个excelorcsv文件。我怎么能做到?
这是我的尝试:
mylist=[[3, 95],[8, 92],[18, 25],[75, 78],[71, 84],-9999,[96, 50],[91, 70],-9999,[19, 60]]
for i in enumerate(mylist):
str1 = ''.join(str(e) for e in mylist)
Run Code Online (Sandbox Code Playgroud)
但是我得到的是整个列表转换为一个字符串,没有区分每个项目:
str1='[3, 95][8, 92][18, 25][75, 78][71, 84]-9999[96, 50][91, 70]-9999[19, 60]'
相反,我想要这样:
str1='[3,95]' #Iter 1
str1='[8, 92]' #Iter 2
str1='[18, 25]' #Iter 3
...
#and so forth
Run Code Online (Sandbox Code Playgroud) 我试图访问给定的文件夹,然后访问其所有子文件夹(20+),然后访问xlsx每个子文件夹内的唯一文件进行一些计算.
我的代码使用load_workbook从openpyxl.我需要一个for循环来读取同一文件夹中的现有文件,但这些文件将其名称从子文件夹更改为子文件夹.为了解决将文件load_workbook的精确名称xlsx作为输入的事实,我选择了这个解决方案:
filename=os.path.basename(file)
wb=load_workbook(filename)
Run Code Online (Sandbox Code Playgroud)
但它引发了这个错误:AttributeError: 'list' object has no attribute 'endswith'.如何解决我的解决方法?
我的完整脚本:
import os
from openpyxl import load_workbook
directoryPath=r'C:\Users\MyName\Desktop\MyFolder'
os.chdir(directoryPath)
folder_list=os.listdir(directoryPath)
for folders, sub_folders, file in os.walk(directoryPath):
for name in file:
if file.endswith(".xlsx"):
filename=os.path.basename(file) #This is supposed to dump the name of the current file to a variable to be used by load_workbook
wb=load_workbook(filename)
cell_range = wb['A1':'A10'] #Accessing some cells
#some calculations
Run Code Online (Sandbox Code Playgroud) 我有一个由10000节点组成的无标度网络,但是边缘的纹理和节点的数量使它太复杂而无法理解。我希望能够在视觉上找到连接最紧密的节点。
如何根据节点的度k为节点着色?具体来说,我想根据预先指定的范围为它们着色,例如:
1<k<10;11<k<20;21<k<30;31<k<40;这是我获取网络的方法:
import networkx as nx
import matplotlib.pyplot as plt
n = 10000 # Number of nodes
m = 3 # Number of initial links
seed = 500
G = nx.barabasi_albert_graph(n, m, seed)
ncols = 100
pos = {i : (i % ncols, (n-i-1)//ncols) for i in G.nodes()}
fig, ax = plt.subplots()
nx.draw(G, pos, with_labels=False, ax=ax, node_size=10)
degrees=G.degree() #Dict with Node ID, …Run Code Online (Sandbox Code Playgroud) 假设我有一个包含n个csv文件的文件夹,我想重命名.新的文件名将是一个类似的ABxxxx,xxxx从1到1000的渐进数字.
在这样做时,我如何保留原始文件扩展名,这是csv什么?
到目前为止我所做的已经改变了文件名,但已经删除了扩展名:
directory=r'C:\Me\MyDir'
subdir=[x[0] for x in os.walk(directory)]
subdir.pop(0)
for i in subdir:
temp_dir=r''+i
os.chdir(temp_dir)
a='A'
b='B'
for file in glob.glob("*.csv"):
for i in range(1,1001):
newname=a+b+i
os.rename(file,newname)
Run Code Online (Sandbox Code Playgroud) 在numpy.ndarray这样的一个:
myarray=
array([[ 0.47174344, 0.45314669, 0.46395022, 0.47440382, 0.50709627,
0.53350065, 0.5233444 , 0.49974663, 0.48721607, 0.46239652,
0.4693633 , 0.47263569, 0.47591957, 0.436558 , 0.43335574,
0.44053621, 0.42814804, 0.43201894, 0.43973886, 0.44125302,
0.41176999],
[ 0.46509004, 0.46221505, 0.48824086, 0.50088744, 0.53040384,
0.53592231, 0.49710228, 0.49821022, 0.47720381, 0.49096272,
0.50438366, 0.47173162, 0.48813669, 0.45032002, 0.44776794,
0.43910269, 0.43326132, 0.42064458, 0.43472954, 0.45577299,
0.43604956]])
Run Code Online (Sandbox Code Playgroud)
我想计算有多少单元格超过给定值,比方说0.5,并设置那些不超过给定值的单元格0.0.这就是我做的:
count=0
value=0.5
for i in range(myarray.shape[0]):
for j in range(myarray.shape[1]):
if myarray[i][j]<value:
myarray[i][j]=0
elif myarray[i][j]>=value:
count=count+1
percentage=round(100*count/(myarray.shape[0]*myarray.shape[1]),2)
Run Code Online (Sandbox Code Playgroud)
但是,我收到这个错误:ValueError: The truth value of an …
我已经尽我最大的能力进行了检查,但没有找到任何kwds可以让您y=a-x在pandas散点图(不一定是最适合的线)上画一条线(例如)并将其放在后面(或前面) )。
#the data frame
ax=df.plot(kind='scatter', x='myX', y='myY',title="Nice title",
xlim=[0,100],ylim=[0,100],figsize=(8,5), grid=True,fontsize=10)
#the line
lnsp=range(0,110,10)
line=[100-i for i in lnsp] #line is y=100-x
ax=line_df.plot(kind='line',color='r',ax=ax,legend=False,grid=True,linewidth=3)
Run Code Online (Sandbox Code Playgroud)
有什么我可以用的吗?或者只是两个东西的绘制顺序?
假设您要创建2D numpy数组,并希望使用顺序整数填充它.有哪些选择?
例:
import numpy
a=numpy.array([[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]])
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我当然可以range(15)用来确定上边界,但如何告诉numpy在5值之后创建一个新行?我正在寻找一个通用的解决方案,因为我的真正问题围绕着一个包含466列和365行的2D数组.
在像这样的简单图形中:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_edge('0','1')
G.add_edge('1','2')
G.add_edge('2','0')
G.add_edge('0','3')
G.add_edge('1','4')
G.add_edge('5','0')
pos={'0':(1,0),'1':(1,1),'2':(2,3),'3':(3,2),'4':(0.76,1.80),'5':(0,2)} #node:(x,y)
nx.draw(G,pos=pos,with_labels=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)
如果我尝试为每个节点分配一个包含节点 ID 及其(x,y)坐标的属性列表,如下所示:
for i,n in enumerate(G.nodes()):
G.nodes()[i]['weight']=[G.nodes()[i],pos[n]] #List of attributes
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
Traceback (most recent call last):
File "<ipython-input-47-0f9ca94eeefd>", line 2, in <module>
G.nodes()[i]['weight']=[G.nodes()[i],pos[n]]
TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
这里有什么问题?
鉴于这种DataFrame:
import pandas as pd
first=[0,1,2,3,4]
second=[10.2,5.7,7.4,17.1,86.11]
third=['a','b','c','d','e']
fourth=['z','zz','zzz','zzzz','zzzzz']
df=pd.DataFrame({'first':first,'second':second,'third':third,'fourth':fourth})
df=df[['first','second','third','fourth']]
first second third fourth
0 0 10.20 a z
1 1 5.70 b zz
2 2 7.40 c zzz
3 3 17.10 d zzzz
4 4 86.11 e zzzzz
Run Code Online (Sandbox Code Playgroud)
我可以创建一个字典,其中包含一系列列作为值,如下所示:
d = {df.loc[idx, 'first']: [df.loc[idx, 'second'], df.loc[idx, 'third']] for idx in range(df.shape[0])}
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能创建一个字典,比如说,一个包含first和second作为键的元组呢?
结果将是:
In[1]:d
Out[1]:
{(0,10.199999999999999): 'a',
(1,5.7000000000000002): 'b',
(2,7.4000000000000004): 'c',
(3,17.100000000000001): 'd',
(4,86.109999999999999): 'e'}
Run Code Online (Sandbox Code Playgroud)
PS:我怎样才能确保这pandas不会扰乱价值观?10.20 现在变成了 10.1999999999...
鉴于此命令numpy.ndarray:
d={0: np.array([[ 9.81650352, 10.03896523, 10.26972675], [11.76386738,
11.76718712, 11.63769531]]),
1: np.array([[ 13.33630352, 29.17866523, 17.1005102675], [41.98976738,
6.44368712, 2.11764771]])}
Run Code Online (Sandbox Code Playgroud)
以下门槛:
t=10
Run Code Online (Sandbox Code Playgroud)
1如果d中的每个浮点值都是>=t,0那么我想要一个新的dict,如果是的话<t.我的尝试
newd={k:[[1]] or [[0]] for k,[[v]] in d if [[v]]>=t}
Run Code Online (Sandbox Code Playgroud)
收益:
Traceback (most recent call last):
File "<ipython-input-152-68383ed9ad79>", line 1, in <module>
newd={k:[[1]] or [[0]] for k,[[v]] in d if [[v]]>=17}
File "<ipython-input-152-68383ed9ad79>", line 1, in <dictcomp>
newd={k:[[1]] or [[0]] for k,[[v]] in d if [[v]]>=17}
TypeError: 'int' object is not iterable …Run Code Online (Sandbox Code Playgroud)