将整列附加到字典中

问题描述 投票:1回答:1

我正在使用数据帧。如果数据框中的列具有一定百分比的空白,我想将该列附加到字典中(并最终将该字典转换为新的数据帧)。

features = {}
percent_is_blank = 0.4


for column in df: 
    x = df[column].isna().mean()
    if x < percent_is_blank:
        features[column] = ??

new_df = pd.DataFrame.from_dict([features], columns=features.keys())

什么会在“??”

python pandas dataframe dictionary
1个回答
1
投票

我认为更好的是用DataFrame.loc过滤:

new_df = df.loc[:, df.isna().mean()  < percent_is_blank]

在您的解决方案中可以使用:

for column in df: 
    x = df[column].isna().mean()
    if x < percent_is_blank:
        features[column] = df[column]
© www.soinside.com 2019 - 2024. All rights reserved.