【问题标题】:how to extract a 2D array encoded in a list of strings in a pandas dataframe?如何提取在熊猫数据框中的字符串列表中编码的二维数组?
【发布时间】:2018-10-13 14:18:27
【问题描述】:

我搞砸了一个数据框。 我有一列包含对数字列表进行编码的字符串

例如

df=
                                    mycol
0   '[ 0.5497076,   0.59722222,  0.42361111]'  
1   '[ 0.8030303,   0.69090909,  0.52727273]'  
2   '[ 0.51461988,  0.38194444,  0.66666667]'

编辑:实际上,逗号也不见了

df=
                                    mycol
0   '[ 0.5497076   0.59722222  0.42361111]'  
1   '[ 0.8030303   0.69090909  0.52727273]'  
2   '[ 0.51461988  0.38194444  0.66666667]'

每个字符串编码一个具有固定数量元素的列表。 我想将此mycol 转换为 3(通常为 N,其中N=len(df[mycol][0]) columns 每个都是数字,包含 mycol 中原始列表中的一个元素

我尝试了以下方法,但没有成功

df[mycol]=df[mycol].apply(lambda s: s.split())
df[mycol]=df[mycol].apply(lambda s: np.fromstring(s))

df[['mycol1','mycol2','mycol3']] = pd.DataFrame(df[mycol].values.tolist(), index= df.index)

【问题讨论】:

    标签: python string list pandas dataframe


    【解决方案1】:

    您可以将列表转换为字典,然后直接将其转换为 DataFrame -

    import re
    def stringtodict(x):
        d = {}
        x = x.replace("[", "").replace("]", "").strip()
        x = re.split("\\s{1,}", x)
        for i in range(len(x)):
            d[str(i)] = float(x[i])
        return d
    
    pd.DataFrame(df['col1'].apply(stringtodict).tolist()) 
    

    我已将空格的代码编辑为分隔符

    【讨论】:

    • 我喜欢你的解决方案,但@Rakesh 最先到达的是非常相似的东西
    【解决方案2】:

    这应该会有所帮助。

    例如:

    import pandas as pd
    df = pd.DataFrame({"mycol": ['[ 0.5497076   0.59722222  0.42361111]', '[ 0.8030303   0.69090909  0.52727273]']})
    df[['mycol1','mycol2','mycol3']]  = df["mycol"].apply(lambda x: x.replace("[", "").replace("]", "").split()).apply(pd.Series)
    print(df)
    

    输出:

                                       mycol     mycol1      mycol2      mycol3
    0  [ 0.5497076   0.59722222  0.42361111]  0.5497076  0.59722222  0.42361111
    1  [ 0.8030303   0.69090909  0.52727273]  0.8030303  0.69090909  0.52727273
    

    【讨论】:

    • 你的回答很好......但是,我的问题有缺陷,因为字符串中没有逗号,所以它还不起作用
    • 这应该会有所帮助。 print(df["mycol"].apply(lambda x: x.replace("[", "").replace("]", "").split()))
    • 您的评论与 df['mycol'].apply(pd.Series) 结合使用。请编辑答案,以便我接受
    • 更新了 sn-p。
    猜你喜欢
    • 2021-11-11
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多