繁体   English   中英

如何在使用 df.astype() 时保留原始 pandas dataframe 值? 我需要为下面的示例提出一个值错误

[英]How do I keep original pandas dataframe values while using df.astype() ? I need to raise a value error for below example

df = pd.DataFrame({ 
'A': ['a', 'b', 'c', 'd', 'e'], 
'B': [1, 2.5, 3, 4, 5], 
'C': ['abc', 'def', 'ghi', 'jkl', 'mno'] })

col_type = {'A':str, 'B':int, 'C':str}

df = df.astype(col_type)
df

Output is:  
    A   B   C
0   a   1   abc
1   b   2   def
2   c   3   ghi
3   d   4   jkl
4   e   5   mno

但我想在 B 列的索引 1 处引发值错误。我不需要 integer 值。 我想自动完成(就像循环遍历所有列)

Panda 内置的.astype() in 似乎没有您想要的“安全转换”方法。

在 numpy 你可以使用np.ndarray.astype(preferred_type, casting='safe')

所以不幸的是,我没有适合你的解决方案,但我会做类似的事情

coltypes = [str,int,str]
colnames = ['a','b','c']
data_for_df =  [df.values[:,i].astype(coltypes[i], casting='safe') for i in range(len(df))]
df = pd.DataFrame(data_for_df,columns=colnames)

可能有人能给出比我更好的答案:)

如果您想控制某些浮点值列仅包含整数,您可以简单地检查原始列与 int 转换后相同列之间的差异:

(df['B'] - df['B'].astype('int')) == 0

给出以下系列:

0     True
1    False
2     True
3     True
4     True
Name: B, dtype: bool

从那里,您可以引发异常

tmp = (df['B'] - df['B'].astype('int')) == 0
if not tmp.all():
    raise TypeError("Non int value at "+ ', '.join(df[(df['B'] - df['B'].astype('int')) != 0]
                     .index.astype(str)))

使用示例数据,它按预期给出:

TypeError: Non int value at 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM