Guf*_*han 7 python 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
Run Code Online (Sandbox Code Playgroud)
由于字符串的 dtype 是“对象”,因此我无法区分字符串和列表(整数或字符串)的列。
如何识别列“Y”是一个整数列表?
jez*_*ael 11
您可以使用applymap、比较然后添加all以检查所有值是否都是Trues:
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
Run Code Online (Sandbox Code Playgroud)
或者:
a = df.applymap(lambda x: isinstance(x, list)).all()
print (a)
X False
Y True
Z False
dtype: bool
Run Code Online (Sandbox Code Playgroud)
如果需要列列表:
L = a.index[a].tolist()
print (L)
['Y']
Run Code Online (Sandbox Code Playgroud)
如果要检查dtypes(但是strings, list,dict是objects):
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
Run Code Online (Sandbox Code Playgroud)
小智 3
如果你的数据集很大,你应该在应用类型函数之前采样,然后你可以检查:
如果最常见的类型是list:
df\
.sample(100)\
.applymap(type)\
.mode(0)\
.astype(str) == "<class 'list'>"
Run Code Online (Sandbox Code Playgroud)
如果所有值都是列表:
(df\
.sample(100)\
.applymap(type)\
.astype(str) == "<class 'list'>")\
.all(0)
Run Code Online (Sandbox Code Playgroud)
如果列表中有任何值:
(df\
.sample(100)\
.applymap(type)\
.astype(str) == "<class 'list'>")\
.any(0)
Run Code Online (Sandbox Code Playgroud)