3 回答
TA贡献1744条经验 获得超4个赞
对元组使用列表推导并传递给 DataFrame 构造函数:
followers = {'realDonaldTrump': [
123456,
123457
],
'BarackObama' : [
999990,
999991,
999992
]}
df = pd.DataFrame([(k, x) for k, v in followers.items() for x in v],
columns=['user','follower'])
print (df)
user follower
0 realDonaldTrump 123456
1 realDonaldTrump 123457
2 BarackObama 999990
3 BarackObama 999991
4 BarackObama 999992
TA贡献1712条经验 获得超3个赞
创建一个兼容的字典:
final_dict = {'users':[], 'followers':[]}
for key in followers:
for i in range(len(followers[key])):
final_dict['users'].append(key)
final_dict['followers'].append(followers[key][i])
df = pd.DataFrame.from_dict(final_dict)
输出:
users followers
0 realDonaldTrump 123456
1 realDonaldTrump 123457
2 realDonaldTrump 123458
3 BarackObama 999990
4 BarackObama 999991
5 BarackObama 999992
TA贡献1799条经验 获得超8个赞
import pandas as pd
followers = {
'realDonaldTrump': [123456, 123457, 123458],
'BarackObama': [999990, 999991, 999992]
}
df = pd.DataFrame()
i = 0
for user in followers:
for r in followers[user]:
df.loc[i, 'user'] = user
df.loc[i, 'record'] = r
i = i + 1
print(df)
结果:
user record
0 realDonaldTrump 123456
1 realDonaldTrump 123457
2 realDonaldTrump 123458
3 BarackObama 999990
4 BarackObama 999991
5 BarackObama 999992
添加回答
举报
