【问题标题】:Failing to convert column in pandas dataframe to integer data type无法将熊猫数据框中的列转换为整数数据类型
【发布时间】:2015-06-22 21:21:40
【问题描述】:

我有这段代码,它通过从现有列中提取信息来操作数据集以创建新列。为了使用 pd.merge 函数与另一个数据集正确匹配数据,我想将“通道 ID”列转换为整数。尽管当前使用 .astype(int),但结果数据类型显示为 float64,查看带有 .info() 的帧

def cost(received_frame):
    received_frame.columns = ['Campaign', 'Ad Spend']
    campaigns = received_frame['Campaign']
    ID = []
    for c in campaigns:
        blocks = re.split('_', c)
        for block in blocks[1:]:
            if len(block) == 6 and block.isdigit(): 
                ID.append(block)
    ID = pd.Series(ID).str.replace("'","")
    ID = pd.DataFrame(ID)
    both = [ID,received_frame]
    frame = pd.concat(both,axis=1)
    frame.columns = ['Channel ID', 'Campaign', 'Ad Spend']
    frame['Channel ID'] = frame['Channel ID'].dropna().astype(int)
    return frame

【问题讨论】:

  • 如果您能分享您正在处理的数据,将会很有帮助。

标签: python pandas


【解决方案1】:

当你写作时

frame['Channel ID'].dropna().astype(int)

您正在返回一个索引可能更少的系列,因为您正在删除 NA。

那么,当你把它赋值为

frame['Channel ID'] = frame['Channel ID'].dropna().astype(int)

它与现有值(根据索引)执行某种合并,这些值是浮点数,因此它也必须转换这些值。

您应该将其替换为其他内容,具体取决于您的问题 (fillna?)。

【讨论】:

  • 明白了!谢谢,但我仍然无法正确合并数据框:(
  • 您能否检查this 问题,如果可能,请创建答案?我认为有必要一些图表或networkx,这对我来说太难了。如果将创建解决方案,我真的很喜欢它;)请让我知道;)谢谢。
  • @jezrael 嗨!我很抱歉,但我现在没有时间(工作)。不过,感谢您的注意!
【解决方案2】:

假设frame 看起来像这样:

import numpy as np
import pandas as pd
frame = pd.DataFrame({'Channel ID':['1',np.nan,'2'], 'foo':['bar','baz',np.nan]})

  Channel ID  foo
0          1  bar
1        NaN  baz
2          2  NaN

您可以从 frame 删除行,其中 Channel ID 是 NaN:

mask = pd.notnull(frame['Channel ID'])
frame = frame.loc[mask]

然后astype(int) 将成功将列转换为dtype int

frame['Channel ID'] = frame['Channel ID'].astype(int)

产量

   Channel ID  foo
0           1  bar
2           2  NaN

正如 Ami Tavory 解释的那样,您不能单独frame['Channel ID'] 中删除 NaN 与

frame['Channel ID'] = frame['Channel ID'].dropna()

因为在赋值时对齐右侧的索引与 左侧的相关行。它对右侧未提及索引的左侧行没有影响。所以 NaN 保留在更大的 DataFrame 中, frame.

由于 NaN 是浮点值,因此只要列包含 NaN,dtype 就必须保持为浮点 dtype。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2019-10-12
    • 2016-01-19
    • 2021-12-18
    • 2017-08-26
    相关资源
    最近更新 更多