Pandas:选择其字典包含特定键的行

时间:2018-02-27 16:31:48

标签: python pandas dictionary dataframe

我有一个数据框,其中一列是所有字典。我想选择其字典包含给定键的行。

app.use(require('./routes/route'));

app.use(function(req, res, next) {
    res.locals.login = req.isAuthenticated();
    res.locals.session = req.session;
    next();
});
require('./config/passport');
app.use(require('./routes'));

2 个答案:

答案 0 :(得分:5)

这是一种方式:

 var query = @"
          SELECT [Country].[CountryId], [Country].[Name] as CountryName, [Province].[ProvinceId], [Province].[Name] as ProvinceName
          FROM [Province]
            RIGHT OUTER JOIN [Country] ON [Province].[CountryId] = [Country].[CountryId]
          WHERE [Country].[CountryId] > 0";

    List<Country> countries = new List<Country>();      

    _connection.Query<Country, Province, Country>(query, (country, province) =>
    {           
        Country lastCountry = countries.FirstOrDefault(d => d.CountryId == country.Id);
        if(lastCountry == null)
        {
            countries.Add(country);
            lastCountry = country;

        }
        lastCountry.Provinces = lastCountry.Provinces.Concat(new List<Province> { province });
        return lastCountry;
    }, null);

    return countries;

<强>解释

  • df = pd.DataFrame({"A": [1,2,3], "B": [{"a":1}, {"b":2}, {"c":3}]}) df = df[df['B'].map(lambda x: 'b' in x)] # A B # 1 2 {'b': 2} 接受匿名(pd.Series.map)函数作为参数。
  • 该函数接受lambda的每个元素并检查B是否在该元素中,返回一个布尔系列。
  • 我们使用b的自然布尔索引来选择所需的行。

答案 1 :(得分:0)

使用获取字典键

df.B.apply(lambda x : 'b' in x.keys())
Out[89]: 
0    False
1     True
2    False
Name: B, dtype: bool