[英]How could I split the result in a column into two separate columns in python?
Assuming you want the ids as your first column and points as the second one, you can do the following:假设您希望将 ids 作为第一列并将点作为第二列,您可以执行以下操作:
df = pd.DataFrame({"top_element_info": [{'id': 123, 'points': 20}, {'id': 124, 'points': 30}, {'id': 125, 'points': 40}]})
for col in ['id', 'points']:
df[col] = [x[col] for x in df['top_element_info']]
I am assuming you want to split the string into two and store it into two columns.我假设您想将字符串分成两部分并将其存储到两列中。 The issue is you are trying to split the string into two columns by assigning expand to True but trying to store it into a single column.
问题是您试图通过将 expand 分配给 True 将字符串拆分为两列,但尝试将其存储到单个列中。
Try:尝试:
events["top_element_info_id"], events["top_element_info_points"] = events["top_element_info"].str.split(",", n = 1, expand = True)
after combining the solutions I've reached this结合解决方案后,我已经达到了这个
events["top_element_info"] = events["top_element_info"].apply(str)
events["top_element_info"].replace(regex=True,inplace=True,to_replace=r"'id':",value=r'')
events["top_element_info"].replace(regex=True,inplace=True,to_replace=r"'points': ",value=r'')
events["top_element_info"].replace(regex=True,inplace=True,to_replace=r"}",value=r'')
events["top_element_info"].replace(regex=True,inplace=True,to_replace=r"}",value=r'')
events[['top_element_info_id', 'top_element_info_points']] = events['top_element_info'].str.split(',', 2, expand=True)
events.head()
and it solved now thanks for all:)现在解决了,谢谢大家:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.