Skip to main content
 首页 » 编程设计

python之是否有一种矢量化的方法来检查 DataFrame 中的值(例如,如果一切都是长度为 0 的字符串)

2025年05月04日36arxive

如果整个列只是长度为 0 或 NaN 的字符串,我想检查数据框的列并更新值。

我知道如何访问每一行和每一列并按每个项目遍历它们,但我想执行的任何操作都应该矢量化(或者至少,尽可能 Pythonic)

import pandas as pd 
import numpy as np 
 
# Create a dataframe for example purposes, filled with data to be left alone 
np.random.seed(0) 
df = pd.DataFrame(np.random.randn(10, 2), columns=['a', 'b'], index=np.random.randint(1,100,10)).sort_index() 
 
# Create an example column that I would modify when encountered in the wild 
df['c'] = '' 
df['d'] = '' 
 
df.iloc[np.random.randint(low=0,high=(len(df)-1)), df.columns.get_loc('c')] = 'Avoid me' 
''' 
THIS IS WHERE THE FUN BEGINS : 
''' 
# If I were to use label-based referencing : 
 
for index, row in df.iterrows(): 
    if len(row['c']) == 0: 
        df.at[index,'c'] = 'Update Me' 
        # df.loc[index]['c'] = 'Update Me' 
 
# or if I were to use position-based referencing : 
 
for i in range(len(df)): 
    if len(df.loc[i,'c']) == 0: 
        df.loc[i,'c'] = 'Update Me' 

这似乎是我最接近目标的方法,但我想确认这是一次检查/更新整个系列的最佳方式。

if (len(df['c'].unique()) == 1) and (df.['c'].unique()[0]==''): 
    df['c'] = 'Update Me' 

这会在指定的列中填充值,但如果除了空字符串之外还有任何值(即仅更改仅填充空白字符串的列),我希望避免使用该列。谢谢Erfan用于输入。

df['c'] = np.where(df['c'].str.len().eq(0), 'Update Me', df['c']) 

请您参考如下方法:

如果您只想检查空字符串,我认为这个单行代码可以满足您的需要:

df.loc[:, (df == '').all()] = 'Update me' 

如果您需要 NaN,只需检查它们是否已填充:

df.loc[:, (df.fillna('') == '').all()] = 'Update me'