在熊猫df列中从左数起两位后添加小数点

时间:2019-02-14 08:15:15

标签: python python-3.x pandas

我有一个类似ind dtype的df。 我想为熊猫df列中的每个值从左数两位后添加小数点

我的女友

Descrip     a         b
VP3         52366599  10718233
VP3         522842650 106751
.
.
VP4         5232937   10542931
VP5         522842650 10615982
.
.

要求

我希望我的Df像

Descrip     a         b
VP3         52.366599  10.718233
VP3         52.2842650 10.6751
.
.
VP4         52.32937   10.542931
VP5         52.2842650 10.615982
.
.

由于数据框内的值没有数字位数,因此我无法通过将每个数字除以10e(某物)来处理简单方法

我希望有一种简单的方法可以解决熊猫中的这一问题

4 个答案:

答案 0 :(得分:2)

您可以使用str迭代列,并在所需位置插入.

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

答案 1 :(得分:2)

我不了解熊猫,但是您可以在 LinearLayout lin = (LinearLayout) convertView.findViewById(R.id.linearChat); final ImageView img1 = new ImageView(context); final TextView tv1 = new TextView(context); tv1.setText(chat.getPesan()); img1.setImageDrawable(context.getResources().getDrawable(R.drawable.cservice)); lin.addView(tv1); tv1.setBackgroundResource(R.drawable.rounded_corner1); tv1.setPadding(10,10,10,10); lin.addView(img1); 模块中使用adjusted方法来解决没有decimal的问题。

str

输出:

import decimal

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

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

    print(x / 10**shift)

答案 2 :(得分:1)

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

num = "1112334254"
new_num = num[:2] +'.'+ num[2:]
print(new_num)

输出应该是这样的:

11.12334254

答案 3 :(得分:1)

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

df['a'] = df['a'].apply(lambda x: x / 10 ** (len((str(x))) - 2))

或者做整个数据框:

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