Python 3.x 将列表理解置于列而不是行之上
我试图将以下循环转换为列表理解:Python 3.x 将列表理解置于列而不是行之上,python-3.x,pandas,type-conversion,list-comprehension,Python 3.x,Pandas,Type Conversion,List Comprehension,我试图将以下循环转换为列表理解: # convert integer-only valued columns from type float to type int for col in df: if sum(df[col]%1) == 0: df[col]=df[col].astype(int) 我似乎无法让这个语法正常工作。这就是我迄今为止所尝试的: new_df = pd.DataFrame([df[col].astype(int) if sum(df[col]%
# convert integer-only valued columns from type float to type int
for col in df:
if sum(df[col]%1) == 0:
df[col]=df[col].astype(int)
我似乎无法让这个语法正常工作。这就是我迄今为止所尝试的:
new_df = pd.DataFrame([df[col].astype(int) if sum(df[col]%1)==0 else df[col] for col in df])
这似乎转换了我的数据帧,而不是实际转换类型。有人能帮我吗?另外,如果有一种更惯用的方法将纯int值列从float转换为int类型,我会选择另一种方法。为什么我们不能使用
np.where
和dict
来映射数据类型,即
df = pd.DataFrame({'co1':[1.,2.,3.,4.],'co2':[2.5,6.5,7.5,1.3]})
df = df.astype(dict(zip(df.columns,np.where((df%1==0).all(),np.int,df.dtypes))))
co1 co2
0 1 2.5
1 2 6.5
2 3 7.5
3 4 1.3
为什么我们不能使用
np.where
和dict
来映射数据类型,即
df = pd.DataFrame({'co1':[1.,2.,3.,4.],'co2':[2.5,6.5,7.5,1.3]})
df = df.astype(dict(zip(df.columns,np.where((df%1==0).all(),np.int,df.dtypes))))
co1 co2
0 1 2.5
1 2 6.5
2 3 7.5
3 4 1.3
您可以使用:
或:
您可以使用:
或:
很高兴能帮助你!我无法将一个系列传递给aType。我不会忘记这个。很高兴能帮助你!我无法将一个系列传递给aType。我不会忘记这个。
df = df.astype(df.dtypes.mask((df%1==0).all(), 'int'))