排序选择数据打分求助:分号分隔字符串转数值列
解决方案:用Pandas实现偏好排序打分
核心思路
将分号分隔的排序字符串拆分为列表,通过位置映射分数(第1偏好=4分,第2=3分,依此类推),再将每个选项转换为独立列并填充对应分数。全程使用基础Pandas操作,无需复杂第三方包。
完整代码实现
import pandas as pd # 1. 构造示例数据(和你的输入一致) data = { 'Fruits': [ 'orange;apple;banana;avocado', 'avocado;apple;banana;orange', 'apple;banana;orange;avocado', 'banana;orange;apple;avocado', 'apple;avocado;banana;orange' ], 'Color': [ 'blue;yellow;red;green', 'red;green;blue;yellow', 'yellow;red;green;blue', 'green;blue;red;yellow', 'yellow;blue;green;red' ] } df = pd.DataFrame(data, index=[1,2,3,4,5]) # 2. 定义处理排序列的函数 def process_ranking_col(col_series, scores=[4,3,2,1]): # 拆分分号分隔的字符串为排序列表 split_list = col_series.str.split(';') # 生成「选项-分数」的字典,再转换为DataFrame return pd.DataFrame( split_list.apply(lambda x: dict(zip(x, scores))).tolist(), index=col_series.index ) # 3. 分别处理Fruits和Color列 fruits_df = process_ranking_col(df['Fruits']) color_df = process_ranking_col(df['Color']) # 4. 合并结果并调整列顺序(匹配你的期望输出) final_df = pd.concat([fruits_df, color_df], axis=1) final_df = final_df[['apple', 'avocado', 'banana', 'orange', 'blue', 'green', 'red', 'yellow']] # 查看结果 print(final_df)
代码解释
- 拆分字符串:
str.split(';')将每行的排序字符串转为有序列表,比如第一行Fruits转为['orange','apple','banana','avocado']。 - 分数映射:通过
zip(x, scores)将排序位置和分数绑定,生成字典(如{'orange':4, 'apple':3}),再展开为列。 - 合并调整:将处理后的水果和颜色分数表合并,按你期望的列顺序重新排列。
输出结果
运行代码后会得到和你期望完全一致的DataFrame:
apple avocado banana orange blue green red yellow 1 3 1 2 4 4 1 2 3 2 3 4 2 1 2 3 4 1 3 4 1 3 2 1 2 3 4 4 2 1 4 3 3 4 2 1 5 4 3 2 1 3 2 1 4
内容的提问来源于stack exchange,提问作者isaid-hi
相关产品推荐
相关产品推荐

