删除数据框列中的非字母str

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了删除数据框列中的非字母str相关的知识,希望对你有一定的参考价值。

假装我有此专栏

energy['Country'] = ['Brazil', 'France (2015)', np.nan, 'USA']

我有一个数据框,其中有一列我要删除带有数字或括号的国家/地区。我特别在for循环中无法删除该值,它抱怨说需要整数。

Energy_Supply = [type(x) == str for x in energy['Country']]  
es = energy['Country'].loc[Energy_Supply]
for k in es:
    if k.isalpha() == False:
        es.pop(k)
energy['Country'] = energy['Country'].where(energy['Country'].isin(es))

我希望您告诉我一种更好更清洁的方式来进行此操作,请解释一下

答案

尝试一下;

# create boolean indexer for alpha only strings 
# this returns a pandas.Series where true is alpha
string_selector = energy['Country'].map(lambda x: x.isalpha() 
                                                  if not isinstance(x, numpy.NaN) 
                                                  else False)

# drop the rows that aren't alpha, notice the ~
energy.drop(energy[~string_selector].index, inplace=True)

以上是关于删除数据框列中的非字母str的主要内容,如果未能解决你的问题,请参考以下文章