【发布时间】:2021-02-11 23:33:02
【问题描述】:
我有一些代码可以将浏览器名称清理为 pandas 数据框列中的短名称,例如“边缘 12345678”变成了“边缘”。
因为我想考虑未来版本的浏览器(版本号会改变),所以我没有使用字典。我使用 pandas loc 函数来识别浏览器名称字段的前两个字母,然后将其替换为短名称(在新列中)。
此代码有效:
df.loc[df['Browser'].str[:2] == 'Ch', 'Browser_type'] = 'Chrome'
df.loc[df['Browser'].str[:2] == 'Mo', 'Browser_type'] = 'Mozilla'
df.loc[df['Browser'].str[:2] == 'Ed', 'Browser_type'] = 'Edge'
df.loc[df['Browser'].str[:2] == 'Fi', 'Browser_type'] = 'Firefox'
df.head()
但我现在正在尝试编写一个函数来执行此操作,并希望将其写成一行。
像这样:
df.loc[df['Browser'].str[:2] == ['Ch'|'Mo'|'Ed'|'Fi'], 'Browser_type'] = ['Chrome'|'Mozilla'|'Edge'|'Firefox']
df.head(3)
但我收到此错误:
TypeError Traceback (most recent call last)
<ipython-input-32-0f4153661736> in <module>
1 df = pd.read_csv ('dummy_webchat_data.csv')
----> 2 df.loc[df['Browser'].str[:2] == ['Ch'|'Mo'|'Ed'|'Fi'], 'Browser_type'] = ['Chrome'|'Mozilla'|'Edge'|'Firefox']
3 df.head(3)
TypeError: unsupported operand type(s) for |: 'str' and 'str'
如果我使用逗号而不是“|”我明白了:
ValueError Traceback (most recent call last)
<ipython-input-33-5ddc9867daf5> in <module>
1 df = pd.read_csv ('dummy_webchat_data.csv')
----> 2 df.loc[df['Browser'].str[:2] == ['Ch','Mo','Ed','Fi'], 'Browser_type'] = ['Chrome','Mozilla','Edge','Firefox']
3 df.head(3)
~\anaconda3\lib\site-packages\pandas\core\ops\common.py in new_method(self, other)
62 other = item_from_zerodim(other)
63
---> 64 return method(self, other)
65
66 return new_method
~\anaconda3\lib\site-packages\pandas\core\ops\__init__.py in wrapper(self, other)
527 rvalues = extract_array(other, extract_numpy=True)
528
--> 529 res_values = comparison_op(lvalues, rvalues, op)
530
531 return _construct_result(self, res_values, index=self.index, name=res_name)
~\anaconda3\lib\site-packages\pandas\core\ops\array_ops.py in comparison_op(left, right, op)
232 # The ambiguous case is object-dtype. See GH#27803
233 if len(lvalues) != len(rvalues):
--> 234 raise ValueError("Lengths must match to compare")
235
236 if should_extension_dispatch(lvalues, rvalues):
ValueError: Lengths must match to compare
请有人帮我用 loc 更有效地写这个吗?
谢谢
M
【问题讨论】:
标签: pandas function rename pandas-loc