jjzjj

python - 如何在 flatMap 函数中实现迭代

coder 2024-01-09 原文

我正在将多行记录文本文件读入 RDD。底层数据是这样的

Time    MHist::852-YF-007   
2016-05-10 00:00:00 0
2016-05-09 23:59:00 0
2016-05-09 23:58:00 0
Time    MHist::852-YF-008   
2016-05-10 00:00:00 0
2016-05-09 23:59:00 0
2016-05-09 23:58:00 0

不,我想转换 RDD,以便获得键映射(时间戳、值)。这可以分几个步骤完成。但我只想在一次调用中提取该信息(但在 Python 2.7 中不是 3)。

RDD是这样的:

[(0, u''),
 (12,
  u'852-YF-007\t\r\n2016-05-10 00:00:00\t0\r\n2016-05-09 23:59:00\t0\r\n2016-05-09 23:58:00\t0\r\n2016-05-09 23:57:00\t0\r\n2016-05-09 23:56:00\t0\r\n2016-05-09 23:55:00\t0\r\n2016-05-09 23:54:00\t0\r\n2016-05-09 23:53:00\t0\r\n2016-05-09 23:52:00\t0\r\n2016-05-09 23:51:00\t0\r\n2016-05-09 23:50:00\t0\r\n2016-05-09 23:49:00\t0\r\n2016-05-09 23:48:00\t0\r\n2016-05-09 23:47:00\t0\r\n2016-05-09 23:46:00\t0\r\n2016-05-09 23:45:00\t0\r\n2016-05-09 23:44:00\t0\r\n2016-05-09 23:43:00\t0\r\n2016-05-09 23:42:00\t0\n'),
 (473,
  u'852-YF-008\t\r\n2016-05-10 00:00:00\t0\r\n2016-05-09 23:59:00\t0\r\n2016-05-09 23:58:00\t0\r\n2016-05-09 23:57:00\t0\r\n2016-05-09 23:56:00\t0\r\n2016-05-09 23:55:00\t0\r\n2016-05-09 23:54:00\t0\r\n2016-05-09 23:53:00\t0\r\n2016-05-09 23:52:00\t0\r\n2016-05-09 23:51:00\t0\r\n2016-05-09 23:50:00\t0\r\n2016-05-09 23:49:00\t0\r\n2016-05-09 23:48:00\t0\r\n2016-05-09 23:47:00\t0\r\n2016-05-09 23:46:00\t0\r\n2016-05-09 23:45:00\t0\r\n2016-05-09 23:44:00\t0\r\n2016-05-09 23:43:00\t0\r\n2016-05-09 23:42:00\t0')]

对于每一对,有趣的部分是值(内容)。在该值中,第一项是键/名称,其余是带有时间戳的值。因此,我正在尝试使用它:

sheet = sc.newAPIHadoopFile(
    'sample.txt',
    'org.apache.hadoop.mapreduce.lib.input.TextInputFormat',
    'org.apache.hadoop.io.LongWritable',
    'org.apache.hadoop.io.Text',
    conf={'textinputformat.record.delimiter': 'Time\tMHist::'}
)

from operator import itemgetter

def process(pair):
    _, content = pair
    if not content: 
        pass

    lines = content.splitlines();
    #k = lines[0].strip()
    #vs =lines[1:]
    k, vs = itemgetter(0, slice(1, None), lines)
    #k, *vs = [x.strip() for x in content.splitlines()]  # Python 3 syntax

    for v in vs:
        try:
            ds, x = v.split("\t")
            yield k, (dateutil.parser.parse(ds), float(x))  # or int(x)
            return
        except ValueError:
            pass

sheet.flatMap(process).take(5)

但是我得到这个错误:

TypeError: 'operator.itemgetter' object is not iterable

进入函数的对具有字符位置(我可以忽略)和内容。内容应按\r\n 拆分,线数组的第一项是键,而其他项则作为 flatMap 的键-时间戳-值。

那么,我的流程方法哪里做错了?

同时,由于 Stackoverflow 和所有其他人的帮助,我想出了这个解决方案。这个工作得很好:

# reads a text file in TSV notation having the key-value no as first column but 
# as a randomly occuring line followed by its values. Remark: a variable might occur in several files

#Time    MHist::852-YF-007   
#2016-05-10 00:00:00 0
#2016-05-09 23:59:00 0
#2016-05-09 23:58:00 0
#Time    MHist::852-YF-008   
#2016-05-10 00:00:00 0
#2016-05-09 23:59:00 0
#2016-05-09 23:58:00 0

#imports
from operator import itemgetter
from datetime import datetime

#read the text file with special record-delimiter --> all lines after Time\tMHist:: are the values for that variable
sheet = sc.newAPIHadoopFile(
    'sample.txt',
    'org.apache.hadoop.mapreduce.lib.input.TextInputFormat',
    'org.apache.hadoop.io.LongWritable',
    'org.apache.hadoop.io.Text',
    conf={'textinputformat.record.delimiter': 'Time\tMHist::'}
)

#this avoid using multiple map/flatMap/mapValues/flatMapValues calls by extracting the values at once
def process_and_extract(pair):
    # first part will be the char-position within the file, which we can ignore
    # second is the real content as one string and not yet splitted
    _, content = pair
    if not content: 
        pass

    try:
        # once the content is split into lines:
        # 1. the first line will have the bare variable name since we removed the preceeding 
        # part when opening the file (see delimiter above)
        # 2. the second line until the end will include the values for the current variable

        # Python 2.7 syntax
        #clean = itemgetter(0, slice(1, None))(lines)
        clean = [x.strip() for x in content.splitlines()]
        k, vs = clean[0], clean[1:]    

        # Python 3 syntax
        #k, *vs = [x.strip() for x in content.splitlines()] 
        #for v in vs*:

        for v in vs:
            try:
                # split timestamp and value and convert (cast) them from string to correct data type
                ds, x = v.split("\t")
                yield k, (datetime.strptime(ds, "%Y-%m-%d %H:%M:%S"), float(x))
            except ValueError:
                # might occur if a line format is corrupt
                pass
    except IndexError:
        # might occur if content is empty or iregular
        pass

# read, flatten, extract and reduce the file at once        
sheet.flatMap(process_and_extract) \
    .reduceByKey(lambda x, y: x + y) \
    .take(5)

第二个版本避免了 for-each-loop,最终快了 20%:

start_time = time.time()

#read the text file with special record-delimiter --> all lines after Time\tMHist:: are the values for that variable
sheet = sc.newAPIHadoopFile(
    'sample.txt',
    'org.apache.hadoop.mapreduce.lib.input.TextInputFormat',
    'org.apache.hadoop.io.LongWritable',
    'org.apache.hadoop.io.Text',
    conf={'textinputformat.record.delimiter': 'Time\tMHist::'}
)

def extract_blob(pair):
    if not pair:
        pass

    try:
        offset, content = pair
        if not content: 
            pass

        clean = [x.strip() for x in content.splitlines()]
        if not clean or len(clean) < 2:
            pass

        k, vs = clean[0], clean[1:]
        if not k:
            pass

        return k.strip(), vs
    except IndexError:
        # might occur if content is empty or malformed
        pass

def extract_line(pair):
    if not pair:
        pass

    key, line = pair;
    if not key or not line:
        pass

    # split timestamp and value and convert (cast) them from string to correct data type
    content = line.split("\t")
    if not content or len(content) < 2:
        pass

    try:
        ds, x = content
        if not ds or not x:
            pass 

        return (key, datetime.strptime(ds, "%Y-%m-%d %H:%M:%S"), float(x))
    except ValueError:
        # might occur if a line format is corrupt
        pass

def check_empty(x):
    return not (x == None)

#drop keys and filter out non-empty entries
non_empty = sheet.filter(lambda (k, v): v)

#group lines having variable name at first line
grouped_lines = non_empty.map(extract_blob)

#extract variable name and split it from the variable values
flat_lines = grouped_lines.flatMapValues(lambda x: x)

#extract the values from the value
flat_triples = flat_lines.map(extract_line).filter(check_empty)

#convert to dataframe
df = flat_triples.toDF(["Variable", "Time", "Value"])

df.write \
    .partitionBy("Variable") \
    .saveAsTable('Observations', format='parquet', mode='overwrite', path=output_hdfs_filepath)

print("loading and saving done in {} seconds".format(time.time() - start_time));

最佳答案

itemgetter 返回一个函数,该函数接受一个对象并为传递给 itemgetter 的每个参数调用 __getitem__。所以你必须在 lines 上调用它:

itemgetter(0, slice(1, None))(lines)

大致相当于

[lines[i] for i in [0, slice(1, None)])

lines[slice(1, None)] 基本上是 lines[1:]

这意味着您必须首先确保 lines 不为空,否则 lines[0] 将失败。

if lines:  # bool(empty_sequence) is False
    k, vs = itemgetter(0, slice(1, None))(lines)
    for v in vs:
        ...

将它们放在一起,包括 doctests:

def process(pair):
    r"""
    >>> list(process((0, u'')))
    []
    >>> kvs = list(process((
    ... 12,
    ... u'852-YF-007\t\r\n2016-05-10 00:00:00\t0\r\n2016-05-09 23:59:00\t0')))
    >>> kvs[0] 
    (u'852-YF-007', (datetime.datetime(2016, 5, 10, 0, 0), 0.0))
    >>> kvs[1]
    (u'852-YF-007', (datetime.datetime(2016, 5, 9, 23, 59), 0.0))
    >>> list(process((
    ... 10,
    ... u'852-YF-007\t\r\n2ad-05-10 00')))
    []
    """ 
    _, content = pair
    clean = [x.strip() for x in content.strip().splitlines()]

    if clean:
        k, vs = itemgetter(0, slice(1, None))(clean)
        for v in vs:
            try:
                ds, x = v.split("\t")
                yield k, (datetime.strptime(ds, "%Y-%m-%d %H:%M:%S"), float(x))
            except ValueError:
                pass 

关于python - 如何在 flatMap 函数中实现迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126919/

有关python - 如何在 flatMap 函数中实现迭代的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby - 在 Ruby 中实现 `call_user_func_array` - 2

    我怎样才能完成http://php.net/manual/en/function.call-user-func-array.php在ruby中?所以我可以这样做:classAppdeffoo(a,b)putsa+benddefbarargs=[1,2]App.send(:foo,args)#doesn'tworkApp.send(:foo,args[0],args[1])#doeswork,butdoesnotscaleendend 最佳答案 尝试分解数组App.send(:foo,*args)

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  8. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  9. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  10. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

随机推荐