我正在尝试使用 openpyxl 读取 excel 工作表。当我像这样阅读时,我想我会丢失工作表中的条件格式信息:
xl = openpyxl.load_workbook(filename)
Run Code Online (Sandbox Code Playgroud)
当我读取文件中的所有单元格并保存时。我得到一个电子表格,其中没有实现任何条件格式。
我可以在http://openpyxl.readthedocs.org/en/latest/formatting.html找到许多向电子表格添加条件格式的方法
但是我找不到在现有工作表中读取条件格式信息的方法。
我用于读写的具体代码是,
import openpyxl as xl
xlf = xl.load_workbook(r'd:\test\book1.xlsx')
sh = xlf.get_sheet_by_name('Sheet1')
allcells = sh.get_cell_collection()
wb = xl.Workbook()
ws = wb.create_sheet()
for c in allcells:
row = c.row
col = xl.cell.column_index_from_string(c.column)
new_cell = ws.cell(row=row, column=col)
new_cell.value = c.value
new_cell.style = c.style.copy()
ws.title = 'test'
wb.save(r'd:\test\book1w.xlsx')
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用python更改Windows系统的目录创建时间戳。我有一个从其他驱动器复制过来的目录,并且目录创建时间没有保留。这就是我希望做的
步骤1:使用以下代码读取源目录列表和创建时间,
import os
source_dir_path = r'd:\data'
list_of_directories = os.listdir(source_dir_path)
creation_times = {}
for d in list_of_directories:
creation_times[d] = os.path.getctime(os.path.join(source_dir_path, d))
Run Code Online (Sandbox Code Playgroud)
步骤2:遍历目录列表并设置目录创建时间。为此,我依靠Python For Windows Extensions。代码如下所示,
from win32file import CreateFile, SetFileTime, GetFileTime, CloseHandle
from win32file import GENERIC_READ, GENERIC_WRITE, OPEN_EXISTING
from pywintypes import Time
destination_dir_path = r'f:\data'
#list_of_directories = os.listdir(source_dir_path)
for d in creation_times:
fh = CreateFile(os.path.join(destination_dir_path,d), 0, 0, None, OPEN_EXISTING, 0,0)
SetFileTime(fh, creation_times[d])
Run Code Online (Sandbox Code Playgroud)
我在CreateFile行上收到“访问被拒绝”。我不确定这是否是设置目录创建时间的有效方法。这是设置目录创建时间的正确方法吗
我正在尝试进行逻辑回归,我的训练数据集来自一个numpy float64数组.我的代码看起来像,
import tensorflow as tf
graph = tf.Graph()
with graph.as_default():
examples =tf.constant(mat6) # mat6 is a numpy float64 array
t_labels = tf.constant(labels) # labels is an a numpy float64 array
W = tf.Variable(tf.truncated_normal([115713, 2]))
b = tf.Variable(tf.zeros([2]))
logits = tf.matmul(examples, W)+b
Run Code Online (Sandbox Code Playgroud)
这引发了一个例外
TypeError: Input 'b' of 'MatMul' Op has type float32 that does not match type float64 of argument 'a'.
Run Code Online (Sandbox Code Playgroud)
这可能是因为W和b是float32而不是float64.有没有办法转换W和b或创建它作为float64
我有一个名为实验的课程和另一个名为案例的课程。一项实验是由许多个别案例组成的。请参阅下面的类定义,
from multiprocessing import Process
class Experiment (object):
def __init__(self, name):
self.name = name
self.cases = []
self.cases.append(Case('a'))
self.cases.append(Case('b'))
self.cases.append(Case('c'))
def sr_execute(self):
for c in self.cases:
c.setVars(6)
class Case(object):
def __init__(self, name):
self.name = name
def setVars(self, var):
self.var = var
Run Code Online (Sandbox Code Playgroud)
在我的实验类中,我有一个名为 sr_execute 的函数。该函数显示了所需的行为。我有兴趣解析所有案例并为每个案例设置一个属性。当我运行以下代码时,
if __name__ == '__main__':
#multiprocessing.freeze_support()
e = Experiment('exp')
e.sr_execute()
for c in e.cases: print c.name, c.var
Run Code Online (Sandbox Code Playgroud)
我明白了,
a 6
b 6
c 6
Run Code Online (Sandbox Code Playgroud)
这是期望的行为。
但是,我想使用多处理并行执行此操作。为此,我将 mp_execute() 函数添加到实验类中,
def mp_execute(self):
processes = []
for c in self.cases: …Run Code Online (Sandbox Code Playgroud) 我在 python 中有一个排序列表(没有重复),就像这样,
l = [1, 3, 5, 8, 9, 11, 13, 17]
Run Code Online (Sandbox Code Playgroud)
我想根据列表值分一杯羹。因此,如果感兴趣的值是 5。那么我想在列表中找到这个值,并在列表中获取它之前的 3 个值。
我可以通过以下功能达到我的目标
def f(k):
if k in l:
i = l.index(k)
return (l[i-2:i+1])
else:
pass
print (f(5))
[1, 3, 5]
print (f(13))
[9, 11, 13]
Run Code Online (Sandbox Code Playgroud)
但是,我有两个问题。如果感兴趣的值不是列表成员,我不知道该怎么办。f(6) 也应该返回 [1,3,5]。我不知道如何在此列表中找到 6
有没有一些“pythonic”的方法来做到这一点
我有一个列表,像这样,
a = ['dog','cat','mouse']
Run Code Online (Sandbox Code Playgroud)
我想构建一个列表,它是所有列表元素的组合,看起来像,
ans = ['cat-dog', 'cat-mouse','dog-mouse']
Run Code Online (Sandbox Code Playgroud)
这就是我提出的,
a = ['dog','cat','mouse']
ans = []
for l in (a):
t= [sorted([l,x]) for x in a if x != l]
ans.extend([x[0]+'-'+x[1] for x in t])
print list(set(sorted(ans)))
Run Code Online (Sandbox Code Playgroud)
是否有更简单,更pythonic的方式!
我正在使用 pandas HDFSTore 对象打开 hdf5 文件并存储DataFrame对象。但在此之前,我想查明该文件是否为空。有没有办法查明我的
In[12]:
import pandas
store = pandas.io.pytables.HDFStore('store.h5')
Out[12]:
<class 'pandas.io.pytables.HDFStore'>
File path: store.h5
Empty
Run Code Online (Sandbox Code Playgroud)
有没有办法浏览 store.h5 中的层次结构树以检查对象是否为空。我想获取 store.h5 中的对象列表
我正在抓住以下代码中的内容.
class foo(object):
def __init__(self,*args):
print type(args)
print args
j_dict = {'rmaNumber':1111, 'caseNo':2222}
print type(j_dict)
p = foo(j_dict)
Run Code Online (Sandbox Code Playgroud)
它产生:
<type 'dict'>
<type 'tuple'>
({'rmaNumber': 1111, 'caseNo': 2222},)
Run Code Online (Sandbox Code Playgroud)
在我看来,这个代码将字典转换为元组!谁能解释一下呢
我正在尝试使用选择键在pandas数据框中选择不同的列
我们说我的数据框是,
import pandas as pnd
s1 = pnd.Series ([0,3,6,7])
s2 = pnd.Series ([1,4,8,9])
s3 = pnd.Series ([2,5,10,11])
df = pnd.DataFrame({'A':s1, 'B':s2, 'C':s3})
A B C
0 0 1 2
1 3 4 5
2 6 8 10
3 7 9 11
Run Code Online (Sandbox Code Playgroud)
我的选择键是,
s4 = pnd.Series (['A','B','C','A'])
0 A
1 B
2 C
3 A
Run Code Online (Sandbox Code Playgroud)
我想要的结果是,
0 0
1 4
2 10
3 7
Run Code Online (Sandbox Code Playgroud)
我想我可以运行for循环来做到这一点
l = []
for idx in df.index:
l.append( df[s4[idx]][idx])
s5 = pnd.Series(l)
print s5
Run Code Online (Sandbox Code Playgroud)
是否有更好/更短/更有效的方式?
我有数据帧和字典.这些看起来像,
import pandas as pd
df1 = pd.DataFrame({'first':['john','oliver','sarah']})
df1_map = {'john': 'anderson', 'oliver': 'smith', 'sarah' : 'shively'}
print (df1)
print (df1_map)
first
0 john
1 oliver
2 sarah
{'oliver': 'smith', 'sarah': 'shively', 'john': 'anderson'}
Run Code Online (Sandbox Code Playgroud)
df1 ['first']的值表示dict的键值.
我想在名为df1 ['second']的数据框中添加第二列,以便维护dict关系以获取以下数据帧,
first last
0 john anderson
1 oliver smith
2 sarah shively
Run Code Online (Sandbox Code Playgroud)
现在,我可以迭代数据帧值,就像这样,
df1['last'] = [ df1_map[i] for i in list(df1['first'])]
Run Code Online (Sandbox Code Playgroud)
我想知道pandas是否支持矢量化实现/函数,它可以在不迭代df行的情况下执行此操作
这是一个最佳实践问题
比方说,我有一个类对象,如下所示:
class ClassOfObjects:
def __init__(self, name):
self.name = name
...
Run Code Online (Sandbox Code Playgroud)
可以说,我实例化了其中的3个对象
a = ClassOfObjects('one')
b = ClassOfObjects('two')
c = ClassOfObjects('three')
Run Code Online (Sandbox Code Playgroud)
现在,我想创建一个我的对象列表.一种显而易见的方法是创建列表对象
ListOfObjects = [a,b,c]
Run Code Online (Sandbox Code Playgroud)
我觉得有限制.特别是当我尝试搜索找到具有特定对象的对象时.有人知道任何最佳做法.
我正在尝试读取和排序具有类似数据的csv文件
Date Open High Low Close Volume
27-Mar-12 8.25 8.35 8.17 8.19 9801989
26-Mar-12 8.16 8.25 8.12 8.24 8694416
23-Mar-12 8.05 8.12 7.95 8.09 8149170
Run Code Online (Sandbox Code Playgroud)
我这样做
import csv
data = csv.reader(open('data.csv','r'))
Run Code Online (Sandbox Code Playgroud)
按日期排序数据.我做:
sorteddata = sorted(data,key=operator.itemgetter(1),reverse=False)
Run Code Online (Sandbox Code Playgroud)
问题是,它通过将日期读取为字符串而不是日期来对日期进行排序.所以数据是这样排序的,
['3-Aug-11', '7.06', '7.23', '6.84', '7.16', '31583617']
['3-Feb-12', '7.02', '7.12', '6.98', '7.08', '15318044']
['3-Jan-12', '5.53', '5.59', '5.44', '5.48', '12678923']
['3-Jun-11', '8.09', '8.17', '7.92', '7.97', '21273812']
['3-May-11', '9.00', '9.04', '8.63', '8.80', '17356005']
Run Code Online (Sandbox Code Playgroud)
有人知道如何按日期排序吗?
我有一个Excel工作表,我想创建一个dict,其单元格值作为列表,单元格列是关键.假设电子表格的数据看起来像,
A B C (columns)
1 2
3 4
5 f
Run Code Online (Sandbox Code Playgroud)
我想要一个看起来像的字典,
cbyc = {'A': [1,3,5]; 'B':[2,4,f]; 'C';[None, None, None]}
Run Code Online (Sandbox Code Playgroud)
我使用以下代码执行此操作
import openpyxl as oxl
wb = oxl.load_workbook('myxlworkbook.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
allcells = sheet.get_cell_collection()
cbyc = {}
for c in allcells:
if c.value is not None:
if c.column not in cbyc.keys():
cbyc[c.column] = [c.value]
else:
cbyc[c.column].append(c.value)
Run Code Online (Sandbox Code Playgroud)
这项工作,...但我相信有一种更有效的方法来创建这个dict与if .. else逻辑
有没有更好的办法?也许openpyxl中有一些东西可以提供这样的列表