Pandas将一个具有多个数据类型的列转换为一个具有一种数据类型的栏



我的数据集的一列确实有问题。我的"标签";列是pandas中的一种对象类型。标签在列表中。现在我想应用一个lambda函数来获取列表的长度。我收到以下错误消息:

类型为"float"的对象没有len((

我分析了数据集,发现我有str、float和None类型。我使用if子句查询了Lambda函数中的None Types。现在我的问题是,我不知道如何统一其他数据类型,所有的数据类型都是List类型。

我尝试了.astype函数,但在那里我得到了以下错误消息:

数据类型'list'不理解

也许有人能给我一个答案:(

编辑:

video_df['tags'].apply(lambda x: 0 if x is None else len(x))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
d:PythonTutorialAnalysisanalysis.ipynb Cell 54' in <cell line: 1>()
----> 1 video_df['tags'].apply(lambda x: 0 if x is None else len(x))
TypeError: object of type 'float' has no len()

仅采样一个值:

'['god of war 3', 'gow', 'santa monica studios', 'sony', 'msony computer entertainment', 'ps3','1080p']'
['bauen',
'insel',
'instrumente'
]

编辑:Celteron-理想输出列当前数据集len 1理想输出len 2具有此功能的电流输出输出:

col  len1  len2
0 '[1, 2, 3]'   3.0  7.0
1         NaN   NaN  <NA>
2          []   0.0     0
3   [1, 2, 3]   3.0     3
4     [1,2,3]   3.0   didnt found one output yet 
5           a   NaN   1.0
6      [test]   1.0   1.0
(col index 4: strangly float objecttype in pandas)

新答案

@mozway指出,df['Tags'].str.len()可以优雅地处理长度未定义的对象!

旧答案

一种解决方法是定义一个自定义函数来处理来自没有定义长度的对象的TypeError。例如,以下函数返回df['Tags']中每个对象的长度,如果对象没有长度,则返回-1:

def get_len(x):
try:
return len(x)
except TypeError:
return -1
df['Tags'].apply(get_len)

我看到了两个主要选项。

  1. 使用适用于所有可迭代项(字符串、列表、元组…(的str.len
  2. 使用循环并检查是否有列表的实例
df = pd.DataFrame({'col': [1,float('nan'),[],[1,2,3],(1,2),'a',['test']]})
# option 1
df['len1'] = df['col'].str.len()
# option 2
df['len2'] = [len(x) if isinstance(x, list) else pd.NA
for x in df['col']]

输出:

col  len1  len2
0          1   NaN  <NA>
1        NaN   NaN  <NA>
2         []   0.0     0
3  [1, 2, 3]   3.0     3
4     (1, 2)   2.0  <NA>
5          a   1.0  <NA>
6     [test]   1.0     1

相关内容

最新更新