pandas - 如何使用熊猫中的列表添加一对多列
问题描述
“fav_colour”和“names”中的第一个列表来自“Tower Hamlets”。
“fav_colour”和“names”中的第二个列表来自“Waltham Forrest”。
请参阅下面的脚本和当前输出:
import pandas as pd
import numpy as np
fav_colour = [['blue', 'yello', 'indigo', 'jasmine', 'green', 'black'], ['yellow','purple', 'red', 'beige']]
names = [['melanie', 'jess', 'sean', 'tom', 'arjun', 'brandon'],['scotty', 'harry', 'chloe', 'emily']]
boroughs = ['Tower Hamlets','Waltham Forrest']
No_of_rows = [len(name) for name in names] #using length to repeat rows in some way??
indexs4 = list(range(0,2))
df1 = [pd.DataFrame(zip(names[i], fav_colour[i], boroughs[i]), columns = ['names','fav', 'boroughs']) for i in indexs4]
df = pd.concat(df1)
“fav_colour”和“names”具有一对一的关系。
“names”和“fav_colour”与自治市镇有一对多的关系
我想与“fav_colour”、“name”和“boroughs”建立一对多的关系,如下所示:
期望的输出:
names fav boroughs
0 melanie blue Tower Hamlets
1 jess yello Tower Hamlets
2 sean indigo Tower Hamlets
3 tom jasmine Tower Hamlets
4 arjun green Tower Hamlets
5 brandon black Tower Hamlets
0 scotty yellow Waltham Forrest
1 harry purple Waltham Forrest
2 chloe red Waltham Forrest
3 emily beige Waltham Forrest
电流输出:
names fav boroughs
0 melanie blue T
1 jess yello o
2 sean indigo w
3 tom jasmine e
4 arjun green r
5 brandon black
0 scotty yellow W
1 harry purple a
2 chloe red l
3 emily beige t
解决方案
import pandas as pd
fav_colour = [['blue', 'yello', 'indigo', 'jasmine', 'green', 'black'], ['yellow','purple', 'red', 'beige']]
names = [['melanie', 'jess', 'sean', 'tom', 'arjun', 'brandon'],['scotty', 'harry', 'chloe', 'emily']]
boroughs = ['Tower Hamlets','Waltham Forrest']
df = pd.DataFrame(columns=['names','fav', 'boroughs'])
for i in range(len(fav_colour)):
tmp = pd.DataFrame(list(zip(names[i],fav_colour[i])),columns=['names','fav'])
tmp["boroughs"] = boroughs[i]
df = df.append(tmp,ignore_index= True)
推荐阅读
- python - 如何在python中实现缓慢更新的侧面输入
- spring - Spring Boot 贝宝 INVALID_RESOURCE_ID
- angularjs - 如何在没有 NPM 的情况下向 angularJS 项目添加依赖项
- swift - rxswift-第一次出错后进入处理包
- php - Laravel 语法错误,意外 T_ENCAPSED_AND_WHITESPACE,期待 T_STRING
- javascript - For循环不工作计数不增加
- python - 使用 python turtle 在仪表上显示值
- javascript - 使用 javascript 价格范围下拉菜单更改文本 onblur
- checkbox - 在 RCPTT 中,如何验证 SWT.CHECK 菜单项的状态?
- javascript - 使用 javascript/jquery 在没有任何用户交互的情况下播放音频