我经常使用 Excel 工作表,我只想将其中的一列特定数字复制到我的 Python 脚本中以进行绘图。这必须手动完成,因为它始终是不同的文件、列和行。
要使用 numpy 数组,我需要带有尾随逗号的数据以这种方式创建 python 数组(我必须添加空格,否则 stackexchange 会将其发布在一行中):
myArray=np.array([
1,
2,
3,
4,
6
)]
因此,在复制 Excel 中的数字列后,我必须手动添加逗号。如果我有大量数据,我会在 Excel 中添加一列,在其中添加所有逗号并将数字与逗号一起复制。不过我觉得应该有更好的方法来做到这一点。
你们知道 python 可能会吞掉我的数据而不用逗号吗?例如
myData = someFunction(
1
2
3
4
6
)
或者您还有其他想法如何更优雅地添加逗号吗?我正在使用 Spyder 和 Python 3。
谢谢!
编辑:如果要求复制一列或一行而不是网格。下面的
in_
可以与replace一起使用来生成逗号分隔的字符串。
# First copy a column from a spread sheet to the clipboard.
# in_() will return the values separated by newlines '\n'.
# replace these by comma
in_()
# Out[21]: '3\n13\n23\n33\n43\n53\n63\n73\n83\n93\n103\n113\n123\n'
in_().replace('\n', ',')
# Out: '3,13,23,33,43,53,63,73,83,93,103,113,123,'
# If copying a row the copied separator is tab '\t'
# Copy a row in a spreadsheet
in_()
# Out: '60\t61\t62\t63\t64\t65\t66\t67\t68\n'
in_().replace('\t', ',')[:-1] # [-1] removes the newline character.
# Out[25]: '60,61,62,63,64,65,66,67,6'
我编写了
in_()
和 from_grid()
将数据从电子表格复制到我想在 python 终端中使用的变量中。它们允许用户将电子表格中的区域复制到剪贴板。 in_()
将以字符串形式返回剪辑。 from_grid()
将返回转换为字符串列表的列表。
import tkinter as tk
import numpy as np
def in_():
"""
Returns the contents of the clipboard as text.
Usage: txt = in_()
"""
clip=tk.Tk()
clip.withdraw()
temp=clip.selection_get(selection="CLIPBOARD")
clip.destroy()
return temp
def from_grid(delimit_row="\n", delimit_cell="\t"):
"""
Returns a list of lists copied from the clipboard.
Usage: grid=from_grid(delimit_row="\t", delimit_cell="\n")
grid is a list of lists
[ [ r00, r01, r02, ... ],
[ r10, r11, r12, ... ],
....
]
by defaut: the row delimiter is a newline, "\n"
the cell delimiter is a tab character, "\t"
This will paste a copied region of a spreadsheet into a list of lists.
"""
txt=in_()
rows=txt.split(delimit_row)
ret=[]
for row in rows:
temp=row.split(delimit_cell)
ret.append(temp)
return ret[:-1] # A final empty last row is appended.
# This loses it.
import numpy as np
def to_floats( data ):
result= []
for row in data:
temp = []
for item in row:
temp.append(float(item))
result.append(temp)
return np.array(result)
arr = to_floats( from_grid() )
这并不完全符合您的要求,但提供了一种将电子表格数据放入 python 中进行处理的方法。
在 python 控制台中运行此命令将让用户打印结果,然后可以将其复制到脚本中。
可能有更巧妙的方法来做到这一点。周围有一些库,Pyperclip 就是其中之一,但我从未使用过它。
将该列复制到 Excel 中,然后在第二列中输入逗号(一直向下复制)。然后将两列复制到spyder中,前后带有“[”和“]”