【问题标题】:converting a column to integer in pandas to prepare for regression在熊猫中将一列转换为整数以准备回归
【发布时间】:2020-01-11 06:42:17
【问题描述】:

我正在为回归准备数据,但我做不到。我必须将 2 行喜欢和流行度转换为整数。我该怎么做。

Unique_ID      int64
Genre          int64
Views          int64
Comments       int64
Likes         object
Popularity    object
Followers      int64
dtype: object

1.我这样做了:

df['Popularity']=df.Popularity.str.replace(',','').astype(int)

错误来了

以 10 为基数的 int() 的无效文字:'13.1K'

  1. 然后我尝试了这个:
pd.to_numeric(df['Likes'], downcast='integer')

错误又来了

无法解析位置 3 处的字符串“2,400”

  1. 还有这个
df = df.astype(int)

以 10 为底的 int() 的无效文字:'2,400'

我可以做些什么来对我的数据进行回归

【问题讨论】:

标签: python pandas


【解决方案1】:

可能有一些格式为13.1K 的条目,因此您也应该从最后一个K 中删除它们。

df['Property'] = df['Property'].str.replace(',','')
df['Property'] = df['Property'].str.rstrip('K')

如果还有其他字符,比如M,去掉它们或使用正则表达式找到它们,然后将它们转换为float

df['Property'] = df['Property'].astype('float64')

您也可以这样做来删除最后一个字母,如下所示:

from string import ascii_letters
df['Property'] = df['Property'].str.rstrip(ascii_letters)

编辑

根据 OP 在 cmets 中提出的要求,以下解决方案将起作用。

假设原始数据集的值如下:

0   13.1K
1   2,400
2   4555
3   6,1M
4   6.1M

使用以下代码

df['Property']=df['Property'].str.replace(',','')
df.['Property'] = (df.['Property'].replace(r'[KM]+$', '',regex=True).astype(float) * \
              df.['Property'].str.extract(r'[\d\.]+([KM]+)', expand=False)
                .fillna(1).replace(['K','M'], [10**3, 10**6]).astype(int))

将数据转换如下

0   13100.0
1   2400.0
2   4555.0
3   61000000.0
4   6100000.0

【讨论】:

  • 我不想剥离它们。我想把 1000 放在有 K 的地方,把 1000000 放在有 M 的地方。谢谢你
  • MemoryError: Unable to allocate array with shape (54920, 40658) and data type int64​然后我尝试了 echo 1 > /proc/sys/vm/overcommit_memory zsh: permission denied: /proc/sys/ vm/overcommit_memory
  • MemoryError 超出了这个问题的范围,但您应该使用sudo 或以root 登录,它可以解决问题。前几天我真的遇到了这个问题,这些 SO 帖子帮助了我:1)stackoverflow.com/questions/57507832/… 2)stackoverflow.com/questions/57812453/…
  • 尝试了 sudo 方法,但没有成功。我尝试了这个 sudo sh -c "/usr/bin/echo 3 > /proc/sys/vm/drop_caches 但仍然无法执行任何操作.同样的错误来了
  • 取决于你的内存,我确实认为在过度提交后错误数字 shape (54920, 40658) 会下降。但是您的内存仍然无法处理如此大的数据集,您可以尝试减小数据集的大小。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-05
  • 1970-01-01
  • 1970-01-01
  • 2019-05-14
  • 1970-01-01
  • 2019-10-12
  • 2013-10-02
相关资源
最近更新 更多