cyr*_*ril 39 python numpy pandas
我已经在Pandas中读取了一个SQL查询,并且这些值以dtype'object'形式出现,尽管它们是字符串,日期和整数.我能够将日期'对象'转换为Pandas datetime dtype,但是在尝试转换字符串和整数时遇到错误.
这是一个例子:
>>> import pandas as pd
>>> df = pd.read_sql_query('select * from my_table', conn)
>>> df
id date purchase
1 abc1 2016-05-22 1
2 abc2 2016-05-29 0
3 abc3 2016-05-22 2
4 abc4 2016-05-22 0
>>> df.dtypes
id object
date object
purchase object
dtype: object
Run Code Online (Sandbox Code Playgroud)
将df['date']日期转换为日期时间:
>>> pd.to_datetime(df['date'])
1 2016-05-22
2 2016-05-29
3 2016-05-22
4 2016-05-22
Name: date, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)
但是在尝试将其转换df['purchase']为整数时出现错误:
>>> df['purchase'].astype(int)
....
pandas/lib.pyx in pandas.lib.astype_intsafe (pandas/lib.c:16667)()
pandas/src/util.pxd in util.set_value_at (pandas/lib.c:67540)()
TypeError: long() argument must be a string or a number, not 'java.lang.Long'
Run Code Online (Sandbox Code Playgroud)
注意:我尝试时遇到类似的错误 .astype('float')
当试图转换为字符串时,似乎没有任何事情发生.
>>> df['id'].apply(str)
1 abc1
2 abc2
3 abc3
4 abc4
Name: id, dtype: object
Run Code Online (Sandbox Code Playgroud)
cyr*_*ril 58
根据@piRSquared的评论记录对我有用的答案.
我需要先转换为字符串,然后转换为整数.
>>> df['purchase'].astype(str).astype(int)
Run Code Online (Sandbox Code Playgroud)
小智 15
df['col_name'] = pd.to_numeric(df['col_name'])
Run Code Online (Sandbox Code Playgroud)
这是一个更好的选择
cs9*_*s95 12
convert_dtypes(自我)接受的答案没有考虑对象列中 NaN 的可能性。
df = pd.DataFrame({
'a': [1, 2, np.nan],
'b': [True, False, np.nan]}, dtype=object)
df
a b
0 1 True
1 2 False
2 NaN NaN
df['a'].astype(str).astype(int) # raises ValueError
Run Code Online (Sandbox Code Playgroud)
这会令人窒息,因为 NaN 被转换为字符串“nan”,进一步尝试强制转换为整数将失败。为避免此问题,我们可以使用以下方法将列软转换为其相应的可为空类型convert_dtypes:
df.convert_dtypes()
a b
0 1 True
1 2 False
2 <NA> <NA>
df.convert_dtypes().dtypes
a Int64
b boolean
dtype: object
Run Code Online (Sandbox Code Playgroud)
如果您的数据中混有垃圾文本和整数,您可以将其pd.to_numeric用作初始步骤:
s = pd.Series(['1', '2', '...'])
s.convert_dtypes() # converts to string, which is not what we want
0 1
1 2
2 ...
dtype: string
# coerces non-numeric junk to NaNs
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 NaN
dtype: float64
# one final `convert_dtypes` call to convert to nullable int
pd.to_numeric(s, errors='coerce').convert_dtypes()
0 1
1 2
2 <NA>
dtype: Int64
Run Code Online (Sandbox Code Playgroud)
这很简单
pd.factorize(df.purchase)[0]
Run Code Online (Sandbox Code Playgroud)
例子:
labels, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])`
Run Code Online (Sandbox Code Playgroud)
labels, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])`
Run Code Online (Sandbox Code Playgroud)
labels
# array([0, 0, 1, 2, 0])
Run Code Online (Sandbox Code Playgroud)
小智 6
我的训练数据包含三个特征是对象,应用后将astype对象转换为数字,但在此之前,您需要执行一些预处理步骤:
train.dtypes
C12 object
C13 object
C14 Object
train['C14'] = train.C14.astype(int)
train.dtypes
C12 object
C13 object
C14 int32
Run Code Online (Sandbox Code Playgroud)
小智 5
要更改数据类型并将其保存到数据框中,需要替换新的数据类型,如下所示:
ds["cat"] = pd.to_numeric(ds["cat"])
Run Code Online (Sandbox Code Playgroud)
或者
ds["cat"] = ds["cat"].astype(int)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
149250 次 |
| 最近记录: |