Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.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 函数将列中的值ex:58K或5m转换为列中的58000或500000_Python - Fatal编程技术网

Python 函数将列中的值ex:58K或5m转换为列中的58000或500000

Python 函数将列中的值ex:58K或5m转换为列中的58000或500000,python,Python,我们在数据框中有一列,其中一些值是5m或5k,然后我想转换这些值,比如5000和5000000 def convert(x): col_number = 0 if 'K' in x: col_number = int(x.replace('K', '')) * 1000 elif 'k' in x: col_number = int(x.replace('k', '')) * 1000 if 'M' in x: col_number =

我们在数据框中有一列,其中一些值是5m或5k,然后我想转换这些值,比如5000和5000000

def convert(x):
     col_number = 0
    if 'K' in x:
    col_number = int(x.replace('K', '')) * 1000
    elif 'k' in x:
    col_number = int(x.replace('k', '')) * 1000
     if 'M' in x:
    col_number = int(x.replace('M', '')) * 1000000
    elif 'm' in x:
    col_number = int(x.replace('m', '')) * 1000000
    else:
    col_number = int(x)
        return int(col_number)

你可以用apply来做

下面是一个运行示例:

import pandas as pd
x = {"number":["1000k","1000K","1M","1m"]}

df = pd.DataFrame.from_dict(x)

def convert(number):
    number = number.lower()
    if "k" in number:
        return int(number.replace("k",""))*1000
    elif "m" in number:
        return int(number.replace("m","")) * 1000000
    return int(number)

df["converted"] = df["number"].apply(convert)
print(df)
输出:
这是一个问题吗?如果是,请明确说明问题的内容?另外,在共享代码时,请使用代码格式,以便其他人能够阅读。是的,问题是,数据框中有一列,其中一些值为5m或5k,然后我想将这些值转换为5000和5000000。我的意思是请将它们添加到问题的主体中。通过在主帖子中添加用户的评论来清除问题。
  number  converted
0  1000k  1000000
1  1000K  1000000
2     1M  1000000
3     1m  1000000