我有這個列,其中一些單元格有兩個值,第一個值是折扣后的價格,第二個值是折扣后的價格。我需要在折扣之前和之后將這些值分成兩個單元格,我嘗試了以下方法,但它們都不起作用,所以如果有人有任何建議如何制作或如何編輯代碼來做到這一點。
列示例:
價格
第 1 行:79.9,99.9
第 2 行:59.9
第 3 行:49.9,89.9
第 4 行:59.9
方法一:
for z in x['1Month Price']:
x['1Month Price'].split(',')
錯誤:
AttributeError Traceback (most recent call last)
<ipython-input-32-1b04b6fed466> in <module>
----> 1 x['1_Month_bf'] = x['1Month Price'].split(',', expand = True)
2 x.head()
~\anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
5463 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5464 return self[name]
-> 5465 return object.__getattribute__(self, name)
5466
5467 def __setattr__(self, name: str, value) -> None:
AttributeError: 'Series' object has no attribute 'split'
方法二:
x['1_Month_bf'] = x['1Month Price'].apply(lambda z: z.split(',')[0])
x.head()
錯誤:
AttributeError Traceback (most recent call last)
<ipython-input-33-aa7ce98376af> in <module>
----> 1 x['1_Month_bf'] = x['1Month Price'].apply(lambda z: z.split(',')[0])
2 x.head()
~\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4136 else:
4137 values = self.astype(object)._values
-> 4138 mapped = lib.map_infer(values, f, convert=convert_dtype)
4139
4140 if len(mapped) and isinstance(mapped[0], Series):
pandas\_libs\lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-33-aa7ce98376af> in <lambda>(z)
----> 1 x['1_Month_bf'] = x['1Month Price'].apply(lambda z: z.split(',')[0])
2 x.head()
AttributeError: 'int' object has no attribute 'split'
uj5u.com熱心網友回復:
嘗試使用str.split. 首先將每行轉換為字串以避免第二個錯誤,然后拆分字串,然后將它們轉換為浮點數。
df[['discount', 'price']] = (
df['1Month Price'].astype(str).str.split(',', expand=True).astype(float)
)
print(df)
# Output
1Month Price discount price
0 79.9,99.9 79.9 99.9
1 59.9 59.9 NaN
2 49.9,89.9 49.9 89.9
3 59.9 59.9 NaN
uj5u.com熱心網友回復:
df[['Price A', 'Price B']] = df['Price'].str.split(',', expand=True)
結果
Price Price A Price B
0 79.9,99.9 79.9 99.9
1 59.9 59.9 None
2 49.9,89.9 49.9 89.9
3 59.9 59.9 None
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454645.html
標籤:Python python-3.x 熊猫 数据框 麻木的
