gpt4 book ai didi

python - 获取数据框中字典的长度

转载 作者:行者123 更新时间:2023-12-02 02:02:39 26 4
gpt4 key购买 nike

我目前正在学习 pandas,想知道如何过滤列(即字典)中包含超过 3 个键的行。例如,

data = {'id':[1,2,3], 'types': [{1: 'a', 2:'b', 3:'c'},{1: 'a', 2:'b', 3:'c', 4:'d'}, {1: 'a', 2:'b', 3:'c'}]}
df = pd.dataframe(data)

如何获取列类型中字典长度> 3的行我尝试做

df[len(df['types']) > 3]

但它不起作用。有什么简单的解决方案吗?

最佳答案

使用Series.applySeries.map :

df = df[df['types'].apply(len) > 3]
#alternative
#df = df[df['types'].map(len) > 3]
print (df)
id types
1 2 {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

或者Series.str.len :

df = df[df['types'].str.len() > 3]

关于python - 获取数据框中字典的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68815720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com