pandas 如何将包含对象的列拆分到多个列中

lsmepo6l  于 2023-05-15  发布在  其他
关注(0)|答案(2)|浏览(135)

我的专栏看起来像这样:

A  B     objectToBeSplit
1  2  {0.223, 0.112, 0.441}
3  4  {0.423, 0.402, 0.593}

我希望它是这样的:

A  B    C      D      E
1  2  0.223  0.112  0.441
3  4  0.423  0.402  0.593

python中如何拆分objectToBeSplit列?

uyto3xhc

uyto3xhc1#

有几种方法可以实现这一点

# Sample DataFrame
df = pd.DataFrame({
    'A': [1, 3],
    'B': [2, 4],
    'objectToBeSplit': ['{0.223, 0.112, 0.441}', '{0.423, 0.402, 0.593}']
})

# Splitting the 'objectToBeSplit' column
df[['C', 'D', 'E']] = df['objectToBeSplit'].str.strip('{}').str.split(', ', expand=True)

# Dropping the original 'objectToBeSplit' column
df = df.drop('objectToBeSplit', axis=1)

方法二:

# Create new columns C, D, E by splitting the values in the "objectToBeSplit" column
df[['C', 'D', 'E']] = pd.DataFrame(df['objectToBeSplit'].tolist()).applymap(float)

# Dropping the original 'objectToBeSplit' column
df = df.drop('objectToBeSplit', axis=1)

# Print the updated DataFrame
print(df)
pjngdqdw

pjngdqdw2#

假设一系列set

out = (df.drop(columns='objectToBeSplit')
         .join(pd.DataFrame(df['objectToBeSplit'].tolist(),
                            columns=['C', 'D', 'E']))
      )

或者,如果您想重新分配到相同的名称:

df = df.join(pd.DataFrame(df.pop('objectToBeSplit').tolist(),
                          columns=['C', 'D', 'E']))

输出:

A  B      C      D      E
0  1  2  0.223  0.112  0.441
1  3  4  0.423  0.402  0.593

可复制输入:

df = pd.DataFrame({'A': [1, 3],
                   'B': [2, 4],
                   'objectToBeSplit': [{0.112, 0.223, 0.441},
                                       {0.402, 0.423, 0.593}],
                   })

相关问题