在阅读CSV文件时,我遇到了NumPy 1.10.2的以下问题.我无法弄清楚如何给出明确的数据类型genfromtxt.
下面是CSV, minimal.csv:
x,y
1,hello
2,hello
3,jello
4,jelly
5,belly
Run Code Online (Sandbox Code Playgroud)
在这里,我尝试用genfromtxt阅读它:
import numpy
numpy.genfromtxt('minimal.csv', dtype=(int, str))
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
import numpy
numpy.genfromtxt('minimal.csv', names=True, dtype=(int, str))
Run Code Online (Sandbox Code Playgroud)
无论如何,我得到错误:
Traceback (most recent call last):
File "visualize_numpy.py", line 39, in <module>
numpy.genfromtxt('minimal.csv', dtype=(int, str))
File "/Users/xeli/workspace/myproj/env/lib/python3.5/site-packages/numpy/lib/npyio.py", line 1518, in genfromtxt
replace_space=replace_space)
File "/Users/xeli/workspace/myproj/env/lib/python3.5/site-packages/numpy/lib/_iotools.py", line 881, in easy_dtype
ndtype = np.dtype(ndtype)
ValueError: mismatch in size of old and new data-descriptor
Run Code Online (Sandbox Code Playgroud)
或者,我试过:
import numpy
numpy.genfromtxt('minimal.csv', dtype=[('x', int), ('y', str)])
Run Code Online (Sandbox Code Playgroud)
哪个投掷:
Traceback (most recent …Run Code Online (Sandbox Code Playgroud) 我想使用新的Java 8流API(对此我一个完整的新手)解析为一个特定的行中的CSV文件(其中以"内达"在名称列).使用以下文章获取动机,我修改并修复了一些错误,以便我可以解析包含3列的文件 - 'name','age'和'height'.
name,age,height
Marianne,12,61
Julie,13,73
Neda,14,66
Julia,15,62
Maryam,18,70
Run Code Online (Sandbox Code Playgroud)
解析代码如下:
@Override
public void init() throws Exception {
Map<String, String> params = getParameters().getNamed();
if (params.containsKey("csvfile")) {
Path path = Paths.get(params.get("csvfile"));
if (Files.exists(path)){
// use the new java 8 streams api to read the CSV column headings
Stream<String> lines = Files.lines(path);
List<String> columns = lines
.findFirst()
.map((line) -> Arrays.asList(line.split(",")))
.get();
columns.forEach((l)->System.out.println(l));
// find the relevant sections from the CSV file
// we are only interested in the row with …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种自动将CSV转换为XML的方法.
以下是CSV文件的示例,其中包含电影列表:
这是XML格式的文件:
<collection shelf="New Arrivals">
<movietitle="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movietitle="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movietitle="Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movietitle="Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>
Run Code Online (Sandbox Code Playgroud)
我已经尝试了几个例子,我可以使用DOM和SAX使用Python读取csv和XML格式,但我找到了一个简单的转换示例.到目前为止,我有:
import csv
f = open('movies2.csv')
csv_f = csv.reader(f)
def convert_row(row):
return """<movietitle="%s">
<type>%s</type>
<format>%s</format>
<year>%s</year>
<rating>%s</rating>
<stars>%s</stars>
<description>%s</description>
</movie>""" % (
row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, …Run Code Online (Sandbox Code Playgroud) 我正在使用CTE将xml转换为csv,以便可以将其导出到文件中,但是如果我有一个空的xml标记,则当前会被忽略.这是我之前非常有用的帖子的初步解决方案:https: //stackoverflow.com/a/23785202/6260721
这是我的sql:
CREATE TABLE EXPORT_TEST
(
DATA varchar(max)
)
INSERT INTO EXPORT_TEST (DATA)
VALUES ('<EXPORT_DATA><ID>ABC123</ID><PRICE_A>5.6</PRICE_A><PRICE_B></PRICE_B><PRICE_C>8.1</PRICE_C></EXPORT_DATA>')
DECLARE @commaSeparatedValues NVARCHAR(MAX)
DECLARE @xml XML = (SELECT TOP 1 CONVERT(xml,DATA) FROM EXPORT_TEST)
;WITH cte AS (
SELECT
rownr = ROW_NUMBER() OVER (ORDER BY @commaSeparatedValues),
Tbl.col.query('.') AS [xml]
FROM @xml.nodes('EXPORT_DATA') Tbl(col)
), cols AS (
SELECT
rownr,
Tbl.Col.value('.', 'nvarchar(max)') AS Value
FROM cte
CROSS APPLY cte.xml.nodes('//text()') Tbl(Col)
)
INSERT INTO EXPORT_TEST(DATA)
SELECT DISTINCT
STUFF((
SELECT ',' + IIF(ISNUMERIC(value) = 1, Value, '''' …Run Code Online (Sandbox Code Playgroud) 我注意到Quantstrat通常采用基于价格的指标.但是,我想加载一些外部计算的指标以及价格数据.例如,我在csv文件中有2个额外的列,其中包含我的指标(编号为1-9).我想根据这些列中的数字生成一个信号.
到目前为止,我无法让Quantstrat读取csv文件中的列.我在下面附上了我的代码:
library(quantmod)
library(quantstrat)
library(PerformanceAnalytics)
library(foreach)
library(FinancialInstrument)
getSymbols("SPY", from = "2015-12-21", to = "2016-12-20", src = "yahoo", adjust =TRUE)
read.csv("/Users/tylerdrust/Downloads/2016 Demark Indicators.csv",
stringsAsFactors = FALSE)
Date Open High Low Close Volume Adj.Close TD.Sell.Count TD.Buy.Count
1 12/21/15 201.41 201.88 200.09 201.67 99094300 197.43 0 0
2 12/22/15 202.72 203.85 201.55 203.50 111026200 199.22 0 0
3 12/23/15 204.69 206.07 204.58 206.02 110987200 201.69 0 0
4 12/24/15 205.72 206.33 205.42 205.68 48539600 201.36 0 0
5 12/28/15 204.86 205.26 203.94 205.21 …Run Code Online (Sandbox Code Playgroud) 我有一个很大的压缩csv文件(25gb),我想将它导入PostgreSQL 9.5版本.有没有快速的方法将zip或qzip文件导入postgres而不解压缩文件?
问题1:如何检查整个.xls或.csv文件是否为空.这是我使用的代码:
try:
if os.stat(fullpath).st_size > 0:
readfile(fullpath)
else:
print "empty file"
except OSError:
print "No file"
Run Code Online (Sandbox Code Playgroud)
空的.xls文件大小超过5.6kb,因此它是否有任何内容并不明显.如何检查xls或csv文件是否为空?
问题2:我需要检查文件的标题.我怎么能告诉python只有一行标题的文件是空的?
import xlrd
def readfile(fullpath)
xls=xlrd.open_workbook(fullpath)
for sheet in xls.sheets():
number_of_rows = sheet.nrows
number_of_columns = sheet.ncols
sheetname = sheet.name
header = sheet.row_values(0) #Then if it contains only headers, treat it as empty.
Run Code Online (Sandbox Code Playgroud)
这是我的尝试.如何继续使用此代码?
请为这两个问题提供解决方案.提前致谢.
我在springboot应用程序中有我的后端,从那里我返回一个.csv文件
@RequestMapping(value = "/downloadCSV")
public void downloadCSV(HttpServletResponse response) throws IOException {
String csvFileName = "books.csv";
response.setContentType("text/csv");
// creates mock data
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
csvFileName);
response.setHeader(headerKey, headerValue);
Book book1 = new Book("Effective Java", "Java Best Practices",
"Joshua Bloch", "Addision-Wesley", "0321356683", "05/08/2008",
38);
Book book2 = new Book("Head First Java", "Java for Beginners",
"Kathy Sierra & Bert Bates", "O'Reilly Media", "0321356683",
"02/09/2005", 30);
Book book3 = new Book("Thinking in Java", "Java Core In-depth",
"Bruce Eckel", "Prentice …Run Code Online (Sandbox Code Playgroud) 我可以使用以下代码将XML转换为CSV:
#read from file
[xml]$inputFile = Get-Content "c:\pstest\test.xml"
#export xml as csv
$inputFile.Transaction.ChildNodes | Export-Csv "c:\pstest\test.csv" -NoTypeInformation -Delimiter:";" -Encoding:UTF8
Run Code Online (Sandbox Code Playgroud)
如果文件只包含一个具有一种子节点类型的根节点,则它可以工作,例如:
<?xml version="1.0" encoding="UTF-8"?>
<Transaction>
<TXNDETAIL>
<RecordID>02</RecordID>
<SequenceNumber>1</SequenceNumber>
<TransactionType>01</TransactionType>
<ActionCode>01</ActionCode>
<TransactionID>17500515552017001</TransactionID>
<SellerCode>2200919TRY</SellerCode>
<BuyerCode>KOCZER</BuyerCode>
<TransactionReference> </TransactionReference>
<TransactionDescription1> </TransactionDescription1>
<TransactionDescription2> </TransactionDescription2>
<DocumentType>01</DocumentType>
<DocumentNumber>XXXXXXXXXXX</DocumentNumber>
<DocumentDate>20170301</DocumentDate>
<DocumentAmount>10000</DocumentAmount>
<CurrencyCode>949</CurrencyCode>
<TransactionAmount>10000</TransactionAmount>
<TransactionDueDate>20170505</TransactionDueDate>
<AdditionalInformation1> </AdditionalInformation1>
<AdditionalInformation2> </AdditionalInformation2>
<HashCode>XXXXXXXX</HashCode>
</TXNDETAIL>
<TXNDETAIL>
<RecordID>02</RecordID>
<SequenceNumber>2</SequenceNumber>
<TransactionType>01</TransactionType>
<ActionCode>01</ActionCode>
<TransactionID>17500515622017001</TransactionID>
<SellerCode>2200919TRY</SellerCode>
<BuyerCode>KOCZER</BuyerCode>
<TransactionReference> </TransactionReference>
<TransactionDescription1> </TransactionDescription1>
<TransactionDescription2> </TransactionDescription2>
<DocumentType>01</DocumentType>
<DocumentNumber>XXXXXXXXXXX</DocumentNumber>
<DocumentDate>20170301</DocumentDate>
<DocumentAmount>10000</DocumentAmount>
<CurrencyCode>949</CurrencyCode>
<TransactionAmount>10000</TransactionAmount>
<TransactionDueDate>20170505</TransactionDueDate>
<AdditionalInformation1> </AdditionalInformation1>
<AdditionalInformation2> </AdditionalInformation2>
<HashCode>XXXXXXXX</HashCode>
</TXNDETAIL>
<TXNDETAIL>
<RecordID>02</RecordID> …Run Code Online (Sandbox Code Playgroud) 这是一个提供便利功能的问题的更新版本
pd_read_printed(str_printed_df)
旨在从之前使用print(some_pandas_DataFrame)编写的字符串中创建一个pandas DataFrame:
Run Code Online (Sandbox Code Playgroud)def pd_read_printed(str_printed_df): global pd, StringIO try: x = pd except: import pandas as pd try: x = StringIO except: from pandas.compat import StringIO return pd.read_csv(StringIO(str_printed_df), delim_whitespace=True)
在我得到以下问题的答案之后,我把它放在一起供自己使用:
我在互联网上经常看到pandas DataFrame在其印刷版中的内容,例如::
df1_as_string = """
Sp Mt Value count
4 MM2 S4 bg 10
5 MM2 S4 dgd 1
6 MM4 S2 rd 2
7 MM4 S2 cb 8
8 MM4 S2 uyi 8
"""
Run Code Online (Sandbox Code Playgroud)
问题是:如何从类似以下样式的字符串变量中获取保存DataFrame的变量:
df1 = pandas.someToMeUnknownPandasFunction(df1_as_string)
Run Code Online (Sandbox Code Playgroud)
?
现在让我们使用提供的函数从df1_as_string以下位置创建DataFrame :
df1 = pd_read_printed(df1_as_string)
Run Code Online (Sandbox Code Playgroud)
并检查它是否按预期工作:
print(df1) …Run Code Online (Sandbox Code Playgroud) csv ×10
python ×4
xml ×3
angular ×1
genfromtxt ×1
import ×1
java ×1
java-8 ×1
java-stream ×1
named-pipes ×1
numpy ×1
pandas ×1
parsing ×1
postgresql ×1
powershell ×1
python-2.7 ×1
python-3.x ×1
quantmod ×1
quantstrat ×1
r ×1
sql ×1
sql-server ×1
string ×1
xlrd ×1
xls ×1