【问题标题】:Python Pandas split big table columnPython Pandas 拆分大表列
【发布时间】:2017-06-21 14:06:02
【问题描述】:

我有一张大桌子(4M 行和 20 列)。在一个特定的列中,我有一个类似的列表:

                                        8 
0       [key1=it, key3=domain, key6=0001]                                                                                              
1                             [key2=home]
2                [key4=pippo, key5=pluto]

给定一个列表 keys=[] 的键,我想以一种有效的方式将“8”列替换为其他列,如下所示:

       key1  key2    key3   key4  key5  key6
0        it  None  domain   None  None  0001
1      None  home    None   None  None  None
2      None  None    None  pippo pluto  None

谢谢! 我

【问题讨论】:

    标签: python pandas


    【解决方案1】:
    s = lambda x: x.split('=')
    rows = df.loc[:, 8].values.tolist()
    pd.DataFrame([dict(map(s, r)) for r in rows])
    
      key1  key2    key3   key4   key5  key6
    0   it   NaN  domain    NaN    NaN  0001
    1  NaN  home     NaN    NaN    NaN   NaN
    2  NaN   NaN     NaN  pippo  pluto   NaN
    

    设置

    df = pd.Series([
            ['key1=it', 'key3=domain', 'key6=0001'],
            ['key2=home'],
            ['key4=pippo', 'key5=pluto']
        ]).to_frame(8)
    

    【讨论】:

    • 谢谢!处理 pd.DataFrame([dict(map(s, r)) for r in rows]) 中的异常存在问题。如果出现问题,我该如何跳过并继续?错误是“ValueError:字典更新序列元素 #0 的长度为 1;需要 2”。
    • 您可以将try/except 放在s 的定义中
    • 那么你必须有不符合你的例子的输入。问另一个包含该示例数据的问题。
    • 我已经解决了坏行的问题,跳过了行。但它是一个 for 循环。
    【解决方案2】:

    我已经通过这种方式解决了坏行的问题,但它是一个for循环:

            self.s = lambda x: x.split('=')
    
            self.rows = self.df.loc[:, 8].values.tolist()
            dictList8 = []
            for idx, self.r in enumerate(self.rows): 
                try:
                    dictList8.append(dict(map(self.s, self.r)))
                except:
                    dictList8.append({'skipped': 'True'})
                    continue
            self.dfMod8 = pd.DataFrame(dictList8)
            del self.df[8]
    

    任何想法如何使它更快?

    【讨论】:

      猜你喜欢
      • 2023-01-27
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 2016-06-15
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多