DataFrame 中某一列是元组形式拆成两列

1.有元组的拆分

df3_new.head()
migrate number1 migrate
0 -11441.0 (北京, 廊坊)
1 -9745.0 (深圳, 惠州)
2 -7393.0 (上海, 苏州)
3 -7053.0 (东莞, 惠州)
4 -4451.0 (北京, 保定)

想把这个里面的migrate拆成两列

#将元组拆包
#dataframe 中某一列是元组形式拆成两列
for i in range (len(df3_new)):
    l1 = [list(j)[0] for j in df3_new['migrate']]
    l2 = [list(k)[1] for k in df3_new['migrate']]
l1
l2
df3_new['地区'] = l1
df3_new['city'] = l2
df3_new
df3_new1 = df3_new.drop('migrate', axis = 1)
df3_new.head()
number1 地区 city
-11441.0 北京 廊坊
-9745.0 深圳 惠州
-7393.0 上海 苏州
-7053.0 东莞 惠州
-4451.0 北京 保定

2.普通拆分:(注:本方法不适用本文档)拆分有逗号隔开的列

df3_new
df3_new['地区'] = df3_new['migrate'].map(lambda x :x.split(',')[0])
df3_new['city'] = df3_new['migrate'].map(lambda x :x.split(',')[1])
df3_new

3.如何遍历一列数组并重新对数组进行编号赋值,形如['a', 'b', 'c', 'c', 'd']变成[1,2,3,3,4]

思路:

#1.将列表用set进行去重

#2.取长度,并生成等长的列表

#3将1,2的结果构建字典

#4对原始的列表进行字典映射

上代码:

city1 = set(list(city)) 
list(city1)[:10]
['遂宁', '北京', '乐山', '菏泽', '毕节', '枣庄', '运城', '吕梁', '吐鲁番', '张家界']
n = [ i for i in range(len(city1))]
c = list(city1)
data= dict(map(lambda x,y:[x,y], c,n))#将节点和标签建立字典
plane['n1'] = plane['地区'].map(data)#map函数将 节点和编号对应 
发布了13 篇原创文章 · 获赞 1 · 访问量 4278

猜你喜欢

转载自blog.csdn.net/weixin_42080294/article/details/89318899