【问题标题】:Split rows of dataframe and store them as individual rows in the same dataframe拆分数据帧的行并将它们作为单独的行存储在同一数据帧中
【发布时间】:2019-10-25 11:27:53
【问题描述】:

我有一个可以使用下面给出的代码创建的数据框

df = pd.DataFrame({'Person_id':[1,2,3,4],
'Values':['father:1.Yes 2.No 3.Do not Know','Mother:1.Yes 777.No 999.Do not 
Know','sons:1.Yes 2.No 321.Do not Know','daughter:1.Yes 567.No 3.Do not Know'],
'Ethnicity':['dffather','dfmother','dfson','dfdaughter']})

上面的代码生成如下所示的数据帧

我想将数据框中每一行的内容拆分为单独的一行

我怎样才能得到这样的输出?

【问题讨论】:

    标签: python regex python-3.x pandas dataframe


    【解决方案1】:

    Series.str.extractall 与正则表达式一起使用以获取带有文本指向Series 的整数值,将第二级由reset_indexDataFrame.join 删除为原始值,最后在必要时通过Series.duplicated 将重复值设置为空字符串:

    cols = df.columns
    s = (df.pop('Values')
           .str.extractall('(\d+\.\D+)')[0]
           .str.strip()
           .reset_index(level=1, drop=True)
           .rename('Values'))
    
    df = df.join(s).reindex(cols, axis=1).reset_index(drop=True)
    df.loc[df['Person_id'].duplicated(), 'Ethnicity'] = ''
    print (df)
        Person_id           Values   Ethnicity
    0           1            1.Yes    dffather
    1           1             2.No            
    2           1    3.Do not Know            
    3           2            1.Yes    dfmother
    4           2           777.No            
    5           2  999.Do not Know            
    6           3            1.Yes       dfson
    7           3             2.No            
    8           3  321.Do not Know            
    9           4            1.Yes  dfdaughter
    10          4           567.No            
    11          4    3.Do not Know            
    

    【讨论】:

    • 你能帮我解决这个问题吗@jezrael - stackoverflow.com/questions/56556191/…
    • 遇到一些问题。因此想到寻求您的帮助。我提供了带有真实数据的错误截图..
    • @AVLES - 是的,但问题是我无法使用其他解决方案......因为不是作者......
    • 好的。我试图找出问题所在。如果你能提供你的解决方案,会很有帮助
    • @AVLES - 好的,所以可以从答案中删除接受,因为不工作?因为接受意味着没有问题,所以不需要另一个答案解决方案......
    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    • 2018-03-03
    • 2020-12-14
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多