转换pandas中列的值

2024-09-29 21:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的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

它们是字符串值。在这个表中,515500是指需要转换成核心的毫核心。39528Mi是Mebibyte,我需要将其转换为gibibyte(或大约)。我想知道如何读取每个值列,以及是否找到m (如5150m),将其转换为岩芯。然后将列的所有值转换为整数,这样我就可以将它们全部相加。在

我想用熊猫,但我对它很陌生。我知道我可以尝试df["col_name"].astype("int")来转换为整数,但我也需要解释millicore值来转换它们。在

任何帮助都是非常感谢的。在

预期输出:所有值都必须是浮点值。我从下面的对话中得知

^{pr2}$

Tags: csv字符串namedf核心格式col整数
3条回答

在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)

我没有找到任何简单的方法,这里有一个肮脏的方法 基本上,列包含不同的字符串(Gi和Mi),需要单独计算。所以,你可以这样做。另外,我在这里没有计算硬CPU列,但是想法是相同的,基本上你可以为它使用相同的模式(比如Used CPU column)。在

df['Used CPU'] = np.where(df['Used CPU'].str.contains('m'),
                          pd.to_numeric(df['Used CPU'].map(lambda x:str(x)[:-1])) /1000,
                          df['Used CPU'])

df['Used Memory'] = np.where(df['Used Memory'].str.contains('Mi'),
                          pd.to_numeric(df['Used Memory'].map(lambda x:str(x)[:-2])) * 0.00104858,
                          df['Used Memory'])

df['Hard Memory'] = np.where(df['Hard Memory'].str.contains('Gi'),
                          pd.to_numeric(df['Hard Memory'].map(lambda x:str(x)[:-2])) *(use math conversion here),
                          df['Hard Memory'])

现在,对于第二列,也有Gi值,所以可以像这样重复相同的内容

^{pr2}$

因为列中的每个项都需要不同的数学转换,如果存在这样的字符串。我能想到的简单可行的解决办法就是这样。很抱歉

你可以这样做。在

更新:

df = pd.read_csv("your_csv_file")

'''df = pd.DataFrame({'Used CPU':['1','0','2','2','0','51550m'], \
                   'Used Memory':['4Gi','0','4Gi','4Gi','0', '39528Mi'], \
                   'Hard CPU':['50','0','4','4','100m','56'], \
                   'Hard Memory':['24Gi','0','8Gi', '8Gi', '128Mi', '47Gi']})'''

units = {'m':0.001,'Mi':0.00104858,'Gi':1.0737425}
def conversion(x):
    for key in units.keys():
        if key in str(x):
            x = x.split(key)[0]
            x = (int(x)*units[key])
            return x
    return str(x)

df = df.applymap(conversion)
df = df.apply(lambda x: x.astype(np.float64), axis=1)
print(df)

输入:

^{pr2}$

输出:

    Hard CPU  Hard Memory  Used CPU  Used Memory
0   50.0      25.76980     1.00      4.29497
1   0.0       0.000000     0.00      0.00000
2   4.0       8.589940     2.00      4.29497
3   4.0       8.589940     2.00      4.29497
4   0.1       0.134218     0.00      0.00000
5   56.0      50.465898    51.55     41.44827

他们在浮动64。现在您可以使用df['Hard Memory'] + df['Used Memory']

相关问题 更多 >

    热门问题