1 回答
TA贡献1946条经验 获得超3个赞
首先,我们应该用索引压平列表,然后使用这样的concat方法pandas:
import pandas as pd
df = pd.DataFrame({"Name":["School","Organisation","Teacher","Guest"]})
From = ['12','18',['11','10'],['12','4','8']]
def flat(nums):
res = []
index = []
for i in range(len(nums)):
if isinstance(nums[i], list):
res.extend(nums[i])
index.extend([i]*len(nums[i]))
else:
res.append(nums[i])
index.append(i)
return res,index
x="From"
list_flat,list_index=flat(eval(x))
dataframe = pd.DataFrame({x:list_flat},index=list_index)
df = pd.concat([df['Name'],dataframe],axis=1,sort=False)
结果是:
Name From
0 School 12
1 Organisation 18
2 Teacher 11
2 Teacher 10
3 Guest 12
3 Guest 4
3 Guest 8
添加回答
举报