【发布时间】: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 的无效文字:'*'