我想确定 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
(但是 strings
、list
、dict
是 object
):
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/