转换 pandas 中列的值

Hee*_*wal 5 python pandas

我有以下格式的 csv

Used CPU    Used Memory Hard CPU    Hard Memory
    1       4Gi         50          24Gi
    0       0           0           0
    2       4Gi         4           8Gi
    2       4Gi         4           8Gi
    0       0           100m        128Mi
    51550m  39528Mi     56          47Gi
Run Code Online (Sandbox Code Playgroud)

它们是字符串值。在此表中,51550m 表示毫核心,我需要将其转换为核心。39528Mi 是 Mebibyte,我需要将其转换为 gibibyte(左右)。我想知道如何逐列读取每个值,如果找到m (如 51550m),请将其转换为核心。然后将列的所有值转换为整数,以便我可以将它们全部相加。

我想使用 pandas,但我对它很陌生。我知道我可以尝试df["col_name"].astype("int")转换为整数,但我还需要解释毫核值来转换它们。

任何帮助深表感谢。

预期输出:所有值都必须是浮点型。我从转换中得到了下面的结果

100 millicore = 1/10 cores
1 Mebibyte = 0.00104858 GB


  Used CPU  Used Memory Hard CPU    Hard Memory
        1       4.296       50          25.7698 
        2       4.296       4           8.592
        2       4.296       4           8.592
        0       0           .1          0.134218 
        51.550  41.448112   56          50.4659
Run Code Online (Sandbox Code Playgroud)

小智 2

在 pandas 中制作自定义函数非常容易。也许你可以尝试这些:

# import
import pandas as pd
# reading file
df = pd.read_csv("PATH_TO_CSV_FILE")

def func_CPU(x):
    """ function for CPU related columns"""
    if x[-1] == "m":
        return float(x[:-1])/1000
    else: return x

def func_Memory(x):
    """ function for Memory related columns"""
    if x[-2:] == "Gi":
        return float(x[:-2]) * 1024 *0.00104858
    elif x[-2:] == "Mi":
        return float(x[:-2]) * 0.00104858
    else: return x



df["Used_CPU"] = df["Used_CPU"].apply(func_CPU)
df["Used_Memory"] = df["Used_Memory"].apply(func_Memory)
df["Hard_CPU"] = df["Hard_CPU"].apply(func_CPU)
df["Hard_Memory"] = df["Hard_Memory"].apply(func_Memory)
print(df)
Run Code Online (Sandbox Code Playgroud)