【问题标题】:Having Trouble Dropping NaN in Pandas [duplicate]在 Pandas 中删除 NaN 时遇到问题 [重复]
【发布时间】:2019-05-02 01:30:42
【问题描述】:

我在将 pandas 数据集中的一列从“对象”更改为“int64”时遇到了很多麻烦。我的 DataFrame 被命名为 bsblendings。

我的 bsblandings.info() 输出如下所示:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 810 entries, 0 to 809
Data columns (total 9 columns):
Year           810 non-null int64
Coast          810 non-null object
Subregion      810 non-null object
State          810 non-null object
Common Name    810 non-null object
Pounds         810 non-null object
Live Pounds    810 non-null object
Dollars        810 non-null object
% Display      810 non-null object
dtypes: int64(1), object(8)
memory usage: 57.0+ KB

我需要使用“磅”列,并且成功地将所有非 int64 值从“*”更改为“0”。我也尝试过使用 numpy 和 NaN。

我用过:

bsblandings = bsblandings.replace('*', ' ')

这并没有将 dtype 从“object”更改为“int64”(尽管所有“*”实际上都被“0”替换了。

然后我尝试使用以下方法对磅列进行排序:

bsblandings.sort_values("Pounds")

我真正需要的只是将磅列从小到大(或从大到小)排序。当我尝试使用 .sort_values 执行此操作时,它没有正确对列进行排序。相反,我得到的输出是 103800、10400、104400、10600:

90  1951    US Atlantic Coast   North Atlantic  MASSACHUSETTS   BASS, BLACK SEA 103800  103800      100%
223 1964    US Atlantic Coast   North Atlantic  MASSACHUSETTS   BASS, BLACK SEA 10400   10400   1687    100%
380 1977    US Atlantic Coast   North Atlantic  MASSACHUSETTS   BASS, BLACK SEA 104400  104400  67172   100%
269 1965    US Atlantic Coast   North Atlantic  MASSACHUSETTS   BASS, BLACK SEA 10600   10600   1379    100%

我是一个菜鸟,我已经搜索了又搜索了,但我一直在碰壁。任何帮助将不胜感激。

【问题讨论】:

  • 你做了bsblandings = bsblandings.sort_values("Pounds") 吗?
  • bsblandings = bsblandings.replace('*', '0')之后尝试bsblandings['Pounds'] = bsblandings['Pounds'].astype('int64')
  • bsblandings['Pounds'] = bsblandings['Pounds'].astype('int64') 产生 ValueError: int() 基数为 10 的无效文字:'*'

标签: python pandas numpy nan


【解决方案1】:

这不是错误:排序是正确的。您的 Pounds 列是字符串格式,所以这是应用的排序。字符串按排序顺序排序,而不是明显的数值。因此,以“103”开头的任何内容都小于以“104”开头的任何内容。

如果您想要数字排序,请将列转换为 int,或指定一个排序键,该键会转换为 int

【讨论】:

  • 有道理!如何将“磅”列转换为 int?
【解决方案2】:

这就解决了!

bsblandings["磅"] = pd.to_numeric(bsblandings["磅"])

谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2022-08-11
    • 1970-01-01
    • 2010-11-12
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多