【问题标题】:Splitting text of a single row into multiple rows of the same column in a CSV file using Python使用Python将单行的文本拆分为CSV文件中同一列的多行
【发布时间】:2019-11-08 06:43:57
【问题描述】:

字典有以下键值对:

    {
    'Target_Tab': 'employees',
    ' Target_Col': 'empp_id  last_name  first_name',
    'Source_Col': 'emp_id    l_name    f_name',
    'Source_Tab': 'employee'
    }

我正在将这本字典写入一个 CSV 文件,到目前为止我已经得到了这个:

Source_Tab   Source_Col                   Target_Tab    Target_Col
employee     emp_id last_name first_name   employees    empp_id l_name f_name 

我想将 Source _col 和 Target_col 值写入不同的行。下面是我需要的:

Source_Tab  Source_Col   Target_Tab  Target_Col
employee    emp_id       employees   empp_id
            last_name                l_name
            first_name               f_name 

我的代码如下:

import pandas as pd
d = [sdict]
d2 = []
col = ["Source_Table","Source_Columns","Target_Table","Target_Columns"]
for i in d:
    temp = {}
    for c in col:
        if c in i:
            temp[c] = i[c]
        else:
            temp[c] = ''
    d2.append(temp)
df2 = pd.DataFrame(d2, columns=col)
df2.to_csv('test21.csv', index=False)

【问题讨论】:

    标签: python pandas csv dictionary


    【解决方案1】:

    将列表推导与split 一起使用以获取Series 的列表并通过concat 连接在一起,最后用DataFrame.fillna 替换缺失值并通过列表col 更改列的顺序:

    d =  {
        'Target_Tab': 'employees',
        'Target_Col': 'empp_id  last_name  first_name',
        'Source_Col': 'emp_id    l_name    f_name',
        'Source_Tab': 'employee'
        }
    
    col = ["Source_Tab","Source_Col","Target_Tab","Target_Col"]
    df = pd.concat([pd.Series(v.split(), name=k) for k, v in d.items()], axis=1).fillna('')[col]
    print (df)
      Source_Tab Source_Col Target_Tab  Target_Col
    0   employee     emp_id  employees     empp_id
    1                l_name              last_name
    2                f_name             first_name
    

    另一种解决方案:

    col = ["Source_Tab","Source_Col","Target_Tab","Target_Col"]
    df = pd.Series(d).str.split(expand=True).fillna('').reindex(col).T
    print (df)
      Source_Tab Source_Col Target_Tab  Target_Col
    0   employee     emp_id  employees     empp_id
    1                l_name              last_name
    2                f_name             first_name
    

    编辑:

    如果需要源字典中的过滤键:

    d =  {
        'Target_Tab': 'employees',
        'Target_Col': 'empp_id  last_name  first_name',
        'Source_Col': 'emp_id    l_name    f_name',
        'Source_Tab': 'employee'
        }
    
    L = ['Source_Tab','Source_Col']
    df = (pd.concat([pd.Series(v.split(), name=k) for k, v in d.items() if k in L], axis=1)
            .fillna(''))
    print (df)
      Source_Col Source_Tab
    0     emp_id   employee
    1     l_name           
    2     f_name           
    

    【讨论】:

    • 不把所有的字典内容都写到d,我怎么只传字典呢? sdict 是我的字典,如果我写 d=[sdict] 我收到错误:AttributeError: 'list' object has no attribute 'items'
    • @shaikhafizunnisa - 添加了新的解决方案
    • 我的错!我正在将字典转换为列表,摆脱了错误。 id .T 在您的新解决方案中做了什么?
    • 还有一种方法可以指定要在哪个键值对上执行此拆分操作?假设我不希望它只在 Source_col 上的 Target_col 上完成。有可能吗?
    • @shaikhafizunnisa - 这里T 表示转置 - DataFrame.T。第二条评论需要在创建DataFrame 之后或之前进行过滤吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多