检查数据系列是否为字符串

Kew*_*ewl 5 python pandas

我想检查数据框中的列是否包含字符串.我原以为这可以通过检查dtype来完成,但事实并非如此.包含字符串的pandas系列只有dtype'object',它也用于其他数据结构(如列表):

df = pd.DataFrame({'a': [1,2,3], 'b': ['Hello', '1', '2'], 'c': [[1],[2],[3]]})

df = pd.DataFrame({'a': [1,2,3], 'b': ['Hello', '1', '2'], 'c': [[1],[2],[3]]})
print(df['a'].dtype)
print(df['b'].dtype)
print(df['c'].dtype)
Run Code Online (Sandbox Code Playgroud)

生产:

int64
object
object
Run Code Online (Sandbox Code Playgroud)

有没有办法检查列是否只包含字符串?

piR*_*red 10

您可以使用它来查看列中的所有元素是否都是字符串

df.applymap(type).eq(str).all()

a    False
b     True
c    False
dtype: bool
Run Code Online (Sandbox Code Playgroud)

要检查是否有任何字符串

df.applymap(type).eq(str).any()
Run Code Online (Sandbox Code Playgroud)