【发布时间】:2021-01-21 22:01:03
【问题描述】:
我有这个 test2 数据框:
manufacturer condition fuel drive cylinders description
0 ford excellent gas rwd NaN ford in excellent condition. 4 cylinders
1 cadillac NaN NaN NaN 4 cylinders 4 cylinders. Half-new cadillac. Diesel.
2 NaN new diesel fwd 12 cylinders Ford, diesel, new condition.
3 NaN NaN electric NaN 10 cylinders Ferrari, excellent condition. 4wd
4 ferrari NaN NaN 4wd NaN New ferrari. Electric with 12 cylinders.
我想遍历数据框并使用“描述”列的信息填充每列的 NaN 值。为此,我这样做了:
import re
manufacturer = '(ford | cadillac | ferrari)'
condition = '(excellent, good, fair, like new, salvage, new)'
fuel = '(gas, hybrid, diesel, electric)'
drive = '(\S*wd)'
cylinders = '(\d+\s+cylinders?)'
test2['manufacturer'] = test2['manufacturer'].fillna(
test2['description'].str.extract(manufacturer, flags=re.IGNORECASE, expand=False)).str.lower()
test2['condition'] = test2['condition'].fillna(
test2['description'].str.extract(condition, flags=re.IGNORECASE, expand=False)).str.lower()
test2['fuel'] = test2['fuel'].fillna(
test2['description'].str.extract(fuel, flags=re.IGNORECASE, expand=False)).str.lower()
test2['drive'] = test2['drive'].fillna(
test2['description'].str.extract(drive, flags=re.IGNORECASE, expand=False)).str.lower()
test2['cylinders'] = test2['cylinders'].fillna(
test2['description'].str.extract(cylinders, flags=re.IGNORECASE, expand=False)).str.lower()
test2
但它看起来不太好,所以我尝试做一个 for 循环来简化编程:
columns = [manufacturer, condition, fuel, drive, cylinders]
for i in test2:
for column in columns:
test2[i] = test2[i].fillna(
test2['description'].str.extract(column, flags=re.IGNORECASE, expand=False)).str.lower()
无论我如何尝试,它都会不断给我错误。它在 test2 中的“i”上循环正常,但是当它开始在列表“columns”上循环时,循环会出错......
知道我该如何解决这个问题吗? 谢谢!
【问题讨论】:
-
该列表应称为
columns,而不是column -
啊对不起,它叫列...
标签: python dataframe for-loop nan