【发布时间】:2023-03-28 20:09:01
【问题描述】:
我正在尝试将下面“odds_df”的“1x2”列中的数据转换为浮点数据类型。
到目前为止,我已经走到了死胡同,似乎没有任何效果……就我的研究和尝试而言。
我需要帮助来克服这个问题,我很高兴我问了:)
ps!我在之前的帖子中忽略了代码 sn-p,希望这次我做对了。
在此处输入代码
import pandas as pd
import pickle
import numpy as np
odds_df = pd.read_csv('betodds.csv')
odds_df.head()
Teams 1x2
0 Leicester City\nManchester United 2.90\n3.50\n2.35
1 Aston Villa\nCrystal Palace 1.90\n3.70\n3.80
2 Fulham FC\nSouthampton FC 3.00\n3.40\n2.30
3 Arsenal FC\nChelsea FC 3.80\n3.70\n1.90
4 Manchester City\nNewcastle United 1.10\n9.50\n22.00
odds_df['1x2'] = odds_df['1x2'].replace('\n',' ', regex=True).values.tolist()
odds_df['1x2']
0 2.90 3.50 2.35
1 1.90 3.70 3.80
2 3.00 3.40 2.30
3 3.80 3.70 1.90
4 1.10 9.50 22.00
5 4.40 3.80 1.75
6 1.70 4.00 4.50
7 2.30 3.30 3.10
------------------------
Name: 1x2, dtype: object
odds_df['1x2'] = pd.to_numeric(odds_df['1x2'])
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
pandas\_libs\lib.pyx in pandas._libs.lib.maybe_convert_numeric()
ValueError: Unable to parse string "2.90 3.50 2.35"
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-74-20aa27752bb5> in <module>
----> 1 odds_df['1x2'] = pd.to_numeric(odds_df['1x2'])
D:\Anaconda\envs\web_scraping\lib\site-packages\pandas\core\tools\numeric.py in to_numeric(arg, errors, downcast)
150 coerce_numeric = errors not in ("ignore", "raise")
151 try:
--> 152 values = lib.maybe_convert_numeric(
153 values, set(), coerce_numeric=coerce_numeric
154 )
pandas\_libs\lib.pyx in pandas._libs.lib.maybe_convert_numeric()
ValueError: Unable to parse string "2.90 3.50 2.35" at position 0
【问题讨论】:
-
你想要的输出是什么?
-
@David Erickson 所需的输出是将列 '1x2' 更改为浮动,以便我可以在代码中对其进行操作。喜欢做数学计算的东西,例如。划分。谢谢
-
看我的回答。一列上有三个不同的值。要使该列成为浮点列,您需要在该列中有一个值,这就是为什么我将其分成 3。您的最终目标是划分三个数字吗?还是倍增?你在尝试什么精确的计算?
-
@David Erickson。我也尝试过 .astype(float) ,它也让我有 ValueError
-
@大卫艾克森。例如,我需要将行中的每个单独的值划分为 1 的数字。这意味着将它们保持在单行格式是理想的,除非它完全没有。希望这是您可以关注的声音。
标签: python-3.x pandas dataframe web-scraping