我有以下数据框(具有1324行):
enter image description here
我需要弄清楚哪些城市适合外卖(“ Take_out”:属性字典中为True)
最佳答案
为了得到这个答案,我首先创建了一个虚拟的DataFrame进行测试:
import numpy as np
import pandas as pd
# create a dictionary list
d = list({'Take-out': True} for x in np.arange(10))
ddf = pd.Series(d, name='attributes')
ddf = pd.DataFrame(ddf)
ddf.index.name = 'cities'
print(ddf)
这提供了与图像中类似的DataFrame。
接下来,遍历DataFrame,如下所示访问“属性”列:
# cities buffer will hold successes
cities = []
# iterate over the list of dictionaries:
for i, each in enumerate(ddf['attributes']):
# check if the keys is in that dictionary, if so, keep the city name
if 'Take-out' in ddf['attributes'][i].keys():
# the index is named 'cities' and each position is a city name, so:
cities.append(ddf.index[i])
print(cities)