如何使用 Pandas 将列中的 1225002 之类的值转换为 1.2M? [英] How to convert a values like 1225002 to 1.2M in a column using pandas?

查看:42
本文介绍了如何使用 Pandas 将列中的 1225002 之类的值转换为 1.2M?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 instagramy 的数据框.数据框由用户名、关注者、关注者、帖子等列组成.

I have got a dataframe using instagramy. The dataframe consists of columns like Usernames, Followers, Following, Posts.

数据框看起来像这样

         Usernames  Followers  Following  Posts
0          A        1225002       1675   5647
1          B        11565253        998  12806
2          C         433688        895    994
3          D        7600455         31  15295
4          E           6706         33    478
5          F           1425        162     12
.          .            .           .       .
.          .            .           .       .
n          n           n            n       n

我想要做的只是将关注者的值从 1225002 转换为 1.2M1156525311.5M这样最终的数据帧将如下所示

What I want to do is simply convert the values of followers from 1225002 to 1.2M 11565253 to 11.5M So that the final dataframe will look like this

         Usernames  Followers  Following  Posts
0          A        1.2M       1675   5647
1          B        11.5M        998  12806
2          C         433K        895    994
3          D        7.6M         31  15295
4          E           6706         33    478
5          F           1425        162     12
.          .            .           .       .
.          .            .           .       .
n          n           n            n       n

我尝试使用 numpy 和 pandas 将绝对数字转换为数字字符串,例如 这些 但我不知道这样做的正确方法.我该怎么做?请帮忙!

I have tried to use numpy and pandas for converting the absolute numbers to a numerical string like these but I do not know the correct way of doing that. How can I do it? Please help!

推荐答案

您可以使用 applylambda 以及 格式化字符串:

You can use apply and lambda along with formatted string:

df['Followers'].apply(lambda x: f'{x/1000000:.1f}M' if x/1000000>=1 else f'{int(x/1000)}K' if x/10000>=1 else f'{x}')

输出:

0     1.2M
1    11.6M
2     433K
3     7.6M
4     6706
5     1425
Name: Followers, dtype: object

这篇关于如何使用 Pandas 将列中的 1225002 之类的值转换为 1.2M?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆