python - 如何识别 pandas 列是一个列表

标签 python pandas numpy dataframe

我想确定 pandas 中的一列是否是一个列表(在每一行中)。

df=pd.DataFrame({'X': [1, 2, 3], 'Y': [[34],[37,45],[48,50,57]],'Z':['A','B','C']})

df
Out[160]: 
   X             Y  Z
0  1          [34]  A
1  2      [37, 45]  B
2  3  [48, 50, 57]  C

df.dtypes
Out[161]: 
X     int64
Y    object
Z    object
dtype: object

由于字符串的 dtype 是“object”,我无法区分是字符串的列还是(整数或字符串的)列表。

如何识别“Y”列是一个 int 列表?

最佳答案

您可以使用 applymap , 比较然后添加 all用于检查所有值是否为 True:

print (df.applymap(type))
               X               Y              Z
0  <class 'int'>  <class 'list'>  <class 'str'>
1  <class 'int'>  <class 'list'>  <class 'str'>
2  <class 'int'>  <class 'list'>  <class 'str'>

a = (df.applymap(type) == list).all()
print (a)
X    False
Y     True
Z    False
dtype: bool

或者:

a = df.applymap(lambda x: isinstance(x, list)).all()
print (a)
X    False
Y     True
Z    False
dtype: bool

如果需要列列表:

L = a.index[a].tolist()
print (L)
['Y']

如果要查dtypes (但是 stringslistdictobject):

print (df.dtypes)
X     int64
Y    object
Z    object
dtype: object

a = df.dtypes == 'int64'
print (a)
X     True
Y    False
Z    False
dtype: bool

关于python - 如何识别 pandas 列是一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45672130/

相关文章:

python - 在另一个模块中使用类/函数

python - 如何使用 python 导入 3d 模型/网格

python - 如何为Python 3.1 ubuntu服务器10.04安装请求​​模块?

python - 使用二元、非二元变量的多元线性回归

Pandas:DataFrame 中的 DataFrame

python - 使用 Pandas 将一行中的所有单元格值转换为字符串

python - 在python或numpy或pandas中,如何将整数分配给字符串

python - 如何使用 Python 正确计算四分位距 (IQR)?

python - 在此 Python 3 客户端-服务器示例中,客户端不能发送多条消息

python - Matplotlib:如何在 Windows 上使背景透明