如何操纵每个索引中的值?

时间:2020-01-03 12:00:37

标签: python pandas numpy data-manipulation data-cleaning

我有一列数字。它具有约60000个索引。一些索引的值如1.000或5.0或2323.0000或1.446。这些索引的正确值为1、5、2323、1446。换句话说,我有两种情况。对于第一种情况,如果索引是带点的数字值,并且该点后为零,则需要删除该点以及该点后的所有零。第二种情况是索引具有带点的数值,但点后的数字不为零。我只需要摆脱点。我该怎么办?

3 个答案:

答案 0 :(得分:2)

我认为您需要:

df = pd.DataFrame({'a':range(5)}, index=[1.0,5.0,2323.0,1.446,10.5])
print (df)
          a
1.000     0
5.000     1
2323.000  2
1.446     3
10.500    4

df.index = df.index.map(lambda x: int(x) if x.is_integer() else int(x * 1000))

或者:

df.index = np.where(df.index.astype(int) == df.index,df.index, df.index * 1000).astype(int)

print (df)
       a
1      0
5      1
2323   2
1446   3
10500  4

或者可能需要:

df.index = df.index.astype(str).str.replace('\.0','').str.replace('.','').astype(int)
print (df)
      a
1     0
5     1
2323  2
1446  3
105   4

答案 1 :(得分:0)

要检查值是否已为整数,请检查How to check if a float value is a whole number

如果不是,则可以乘以直到达到。之后,在两种情况下都可以转换为int。

答案 2 :(得分:0)

这可能不是最优雅的解决方案,但它简单干净,没有导入内容,只有基本的python

outcome = []
for i in raw:
    if i%1 == 0: # check if number is whole
        outcome += int(i) # append normally as int
    else:
        outcome += int(str(i).replace('.','')) #replace .
return outcome

可能是

return [(int(i) if i.is_integer() else int(str(i).replace('.',''))) for i in raw]