zidian=['刘友德','熊剑','张明泽','朱淑贞','涂敬','黄德明','闫凌博','刘翠芳'],
df = pd.DataFrame({
'人名': ['(刘友德熊剑)张明泽朱淑贞涂敬黄德明闫凌博刘翠芳',
'(刘友德)刘友德郑旭祥',
'(刘友德熊剑)张明泽李扶新林春媚']
}),
python如何根据zidian去把人名分成单独的列
import pandas as pd
zidian = ['刘友德', '熊剑', '张明泽', '朱淑贞', '涂敬', '黄德明', '闫凌博', '刘翠芳']
df = pd.DataFrame({
'人名': ['(刘友德熊剑)张明泽朱淑贞涂敬黄德明闫凌博刘翠芳', '(刘友德)刘友德郑旭祥', '(刘友德熊剑)张明泽李扶新林春媚']
})
def split_names(name_str, names_list):
result = []
start_idx = 0
for name in names_list:
idx = name_str.find(name, start_idx)
if idx != -1:
if idx > start_idx:
# 如果找到了名字,并且它前面还有字符,则添加一个占位符(如None)
result.append(None)
result.append(name)
start_idx = idx + len(name)
else:
# 如果名字没有在当前位置找到,则添加一个占位符(如None)
result.append(None)
# 如果字符串的末尾还有剩余字符,则添加为最后一个名字(可能是错误的,需要进一步的逻辑来确定)
if start_idx < len(name_str):
result.append(name_str[start_idx:])
return result
# 应用split_names函数到df的'人名'列,并创建新的列
for i, name in enumerate(zidian):
df[name] = df['人名'].apply(lambda x: split_names(x, zidian)[i] if i < len(split_names(x, zidian)) else None)
# 删除原来的'人名'列
df = df.drop(columns=['人名'])
# 显示结果
print(df)