Python pandas:将字典值级联到DataFrame列时遇TypeError求助
问题解决
错误根源及修复步骤
DataFrame创建语法错误
原始代码中创建DataFrame的列表里,子列表之间缺少逗号,Python会将相邻两个列表解析为索引操作(如list1[list2]),从而抛出TypeError: list indices must be integers or slices, not tuple。修复后代码:
df = pd.DataFrame({'key' : [['vs', 'vscode'], ['jupyter and jupyterlab', 'python'], ['python'], ['it was spyder before dawn']]})函数逻辑错误
cascade_col函数中,row_value是列表类型,没有split()方法;同时列表内的元素可能是包含多个单词的字符串,需要先拆分这些字符串为单个单词,再匹配字典键。修复后函数:
def cascade_col(row_value): cvc_row = [] for item in row_value: # 将每个字符串拆分为单词 for word in item.split(): if word in my_dict: cvc_row.append(my_dict[word]) return cvc_row
完整可运行代码
import pandas as pd # 修复语法错误的DataFrame创建 df = pd.DataFrame({'key' : [['vs', 'vscode'], ['jupyter and jupyterlab', 'python'], ['python'], ['it was spyder before dawn']]}) my_dict = {'vscode' : 'is awesome', 'spyder' : 'is not so awesome, but hes ok, ig', 'vs' : 'is gross', 'same' : 'can fly'} # 修复逻辑的函数 def cascade_col(row_value): cvc_row = [] for item in row_value: for word in item.split(): if word in my_dict: cvc_row.append(my_dict[word]) return cvc_row df['dict value'] = df['key'].apply(cascade_col) print(df)
运行结果
key dict value 0 [vs, vscode] [is gross, is awesome] 1 [jupyter and jupyterlab, python] [] 2 [python] [] 3 [it was spyder before dawn] [is not so awesome, but hes ok, ig]
内容的提问来源于stack exchange,提问作者ahhhgetit
相关产品推荐
相关产品推荐

