我试图对包含列表的数据帧列(称为dimensions
)执行一些基本操作。当dataframe列包含列表时,像df['dimensions'].str.replace()
这样的基本操作是否有效?这对我不起作用。我还尝试使用re.sub()
方法替换列中的文本,但也不起作用
这是我的数据框中的最后一列:
**dimensions**
[50' long]
None
[70ft long, 19ft wide, 8ft thick]
[5' high, 30' long, 18' wide]
这是我尝试过的,但没有成功:
def dimension_unique_words(dimensions):
if dimensions != 'None':
for value in dimensions:
new_value = re.sub(r'[^\w\s]|ft|feet', ' ', value)
new_value = ''.join([i for i in new_value if not i.isdigit()])
return new_value
df['new_col'] = df['dimensions'].apply(dimension_unique_words)
这是我从代码中获得的输出:
**new_col**
NaN
None
NaN
None
NaN
None
我想做的是用空格替换名为dimensions
的列中的数字和单位[ft,feet',],然后在该列上应用df.unique()
以获得唯一的值,即[long,wide,thick,high]
预期输出为:
**new_col**
[long]
None
[long, wide, thick]
[high, long, wide]
…然后我想在new_col
上应用df.unique()
得到[长、宽、厚、高]
怎么做
首先,我们要处理的麻烦是,您的“维度”列有时是无的,有时是一个字符串元素的列表。因此,当元素为非null时,提取该元素:
接下来,获取每行中的所有字母字符串,不包括测量值:
注意,我们使用
\b
单词边界(从“30ft”中排除“ft”),为了避免将\b
误解为反斜杠,我们必须在正则表达式上使用r''rawstring首先,我们要处理的麻烦是,您的“维度”列有时是无的,有时是一个字符串元素的列表。因此,当元素为非null时,提取该元素:
接下来,获取每行中的所有字母字符串,不包括测量值:
注意,我们使用
\b
单词边界(从“30ft”中排除“ft”),为了避免将\b
误解为反斜杠,我们必须在正则表达式上使用r''rawstring这会给你一个列表。您需要一个集合,以防止重复发生,因此:
str.findall
查找列表中的所有维度值李>explode
将列表分解为具有相同索引的元素李>groupby(level=0).unique()
将重复项按索引放到列表中李>使用
df['new_col'].explode().dropna().unique()
获取唯一的维度值相关问题 更多 >
编程相关推荐