Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在列中左起两位数后添加小数点_Python_Python 3.x_Pandas - Fatal编程技术网

Python 在列中左起两位数后添加小数点

Python 在列中左起两位数后添加小数点,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个类似下面的带有int-dtype的df。 我想在df列中每个值的左起两位数后加上小数点 我的Df 要求 我希望我的Df像 Descrip a b VP3 52.366599 10.718233 VP3 52.2842650 10.6751 . . VP4 52.32937 10.542931 VP5 52.2842650 10.615982 . . 由于数据帧中的值没有相同的位数,因此我无法通

我有一个类似下面的带有int-dtype的df。 我想在df列中每个值的左起两位数后加上小数点

我的Df 要求 我希望我的Df像

Descrip     a         b
VP3         52.366599  10.718233
VP3         52.2842650 10.6751
.
.
VP4         52.32937   10.542931
VP5         52.2842650 10.615982
.
.
由于数据帧中的值没有相同的位数,因此我无法通过将每个数字除以10esomething的简单方法进行处理


我希望在pandas中有一个简单的方法来解决这个问题

您可以使用str和insert迭代列。在所需位置:

df = pd.DataFrame(np.random.randint(0, 2000, (5, 2)))
print(df)
      0     1
0    97   148
1   796   935
2  1992   594
3  1498   416
4    34  1289

df = df.astype(str)
for c in df:
    df[c] = (df[c].str[:2] + '.' + df[c].str[2:]).astype(float)
print(df)
       0      1
0  97.00  14.80
1  79.60  93.50
2  19.92  59.40
3  14.98  41.60
4  34.00  12.89

如果我正确回答了您的问题,您可以将每个数字转换为字符串,然后在您希望的每个索引处添加点或逗号:

num = "1112334254"
new_num = num[:2] +'.'+ num[2:]
print(new_num)
输出应如下所示:

11.12334254

仅使用字符串长度进行浮点除法可能会更快:

df['a'] = df['a'].apply(lambda x: x / 10 ** (len((str(x))) - 2))
或者执行整个数据帧:

df.applymap(lambda x: x / 10 ** (len((str(x))) - 2))

我不知道,但是你可以使用十进制模块中的调整方法来解决没有str的问题

输出:

52.366599
10.718233
52.284265
10.6751
52.32937
10.542931
52.284265
10.615982

您可能应该添加一个条件来处理小于10的值。
import decimal

for x in [52366599, 10718233,
          522842650, 106751,
          5232937, 10542931,
          522842650, 10615982]:

    shift = decimal.Decimal(x).adjusted() - 1

    print(x / 10**shift)
52.366599
10.718233
52.284265
10.6751
52.32937
10.542931
52.284265
10.615982