Skip to main content
 首页 » 编程设计

python之逐元素向下转换系列或数据框

2024年10月17日8duanxz

考虑pd.DataFrame df

df = pd.DataFrame([ 
        [1.0, 1.5], 
        [2.2, 3.0] 
    ]) 

如果它们相等,我想将单个元素向下转换为 int。我知道每一列最终都会成为对象类型。没关系。

<class 'pandas.core.frame.DataFrame'> 
RangeIndex: 2 entries, 0 to 1 
Data columns (total 2 columns): 
0    2 non-null object 
1    2 non-null object 
dtypes: object(2) 
memory usage: 112.0+ bytes 

请您参考如下方法:

您需要先将dtype 转换为object,然后您可以使用掩码使用astype(int) 覆盖感兴趣的值> 在 df 上假设所有列都是数字:

In [120]: 
df = df.astype(object) 
df[df == df.astype(int)] = df.astype(int) 
df 
 
Out[120]: 
     0    1 
0    1  1.5 
1  2.2    3 

没有 Actor ,分配保持 float

可以看到个别类型发生了变化:

In [123]: 
df.applymap(type) 
 
Out[123]: 
                 0                1 
0    <class 'int'>  <class 'float'> 
1  <class 'float'>    <class 'int'>