【发布时间】:2020-08-19 19:32:45
【问题描述】:
我有一个这样的数据框
# initialize list of lists
data = [[1, ['ABC', 'pqr']], [2, ['abc', 'XY']], [3, np.nan]]
# Create the pandas DataFrame
data = pd.DataFrame(data, columns = ['Name', 'Val'])
data
Name Val
0 1 [ABC, pqr]
1 2 [abc, XY]
2 3 NaN
我正在尝试将列表中的每个值都转换为小写
data['Val'] = data['Val'].apply(lambda x: np.nan if len(x) == 0 else [item.lower() for item in x])
data
但是我得到了这个错误
TypeError: object of type 'float' has no len()
预期的最终输出
Name Val
0 1 [abc, pqr]
1 2 [abc, xy]
2 3 NaN
【问题讨论】:
-
你要转义
NaN,看看this post。 -
你可以使用
lambda x: np.nan if x is np.NaN else [item.lower() for item in x]。 -
Henry,你的答案是正确的,如果你能把它写成答案,将不胜感激
-
@Max 我犯了什么错误
-
我也收到此错误 -
TypeError: 'float' object is not iterable
标签: python-3.x pandas dataframe