python - Split dataframe column containing list inside a string to two columns
问题描述
I have a df where one column, 'vals' contains a list inside a string. I want to convert this into two columns 'val1' and 'vals2. I have tried to split and strip the string but can't find an implementation to do this for every row in the df.
vals
'[12.1, 15.0]'
val1 val2
12.1 15.0
解决方案
Use strip
with split
and casting to floats if necessary, last add prefix by add_prefix
:
df = pd.DataFrame({'vals':["'[12.1, 15.0]'","'[12.1, 15.0]'"]})
df = (df['vals'].str.strip("'[]")
.str.split(', ', expand=True)
.astype(float)
.add_prefix('val'))
If no missing values and performance is important:
df = pd.DataFrame([x.strip("'[]").split(', ') for x in df['vals']],
columns = ['val1', 'val2']).astype(float)
推荐阅读
- python - 如何解决 heroku flask 应用程序上的应用程序错误?
- visual-studio - 如何从 Visual Studio 将参数传递给 MSBuild?
- android - 适用于 Android 11 目标的离线提醒通知应用程序(Google Keep 之类)。应用关闭时如何接收通知?
- c# - 在asp.net中将大量数据从视图发送到控制器
- c# - Blazor 如何使用获取请求
- function - Flutter/cloud_firestore:未为 Map 类型定义运算符“[]”
功能() - reactjs - useState 的问题 - 修改后的状态没有立即反映
- latex - 在 Beamer 演示文稿中插入 Jypyter Lab 代码片段
- python-3.x - 为 CDC Wonder API 抓取用户门户
- swift - 从其嵌套类型推断泛型类型