【发布时间】:2019-04-28 18:17:49
【问题描述】:
我有以下数据框(有 1324 行): enter image description here
我需要弄清楚哪些城市适合外卖('Take_out':属性字典中为真)
【问题讨论】:
-
欢迎来到 SO!请不要发布数据或代码的图像 - 给出文本。另外,请记住问题应该有一个MCVE
标签: python
我有以下数据框(有 1324 行): enter image description here
我需要弄清楚哪些城市适合外卖('Take_out':属性字典中为真)
【问题讨论】:
标签: python
为了得到这个答案,我首先创建了一个用于测试的虚拟 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)
【讨论】:
字典并不是您真正想要存储在 DataFrame 中的内容,但您可以尝试:
df = df.assign(**df.attributes.dropna().apply(pd.Series))
df[df["Take_out"] == True]
这与此处描述的想法大致相同:Unpack dictionary from Pandas Column。解压该字典后,我们可以像往常一样选择带有 "Take_out" == True 的行。
【讨论】: