无法比较/转换lis

2024-06-01 06:19:44 发布

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

我有一列“Employees”,其中包含以下数据:

122.12 (Mark/Jen)
32.11 (John/Albert)
29.1 (Jo/Lian)

我需要计算有多少值与特定条件匹配(如x>31

base = list()
count = 0
count2 = 0

for element in data['Employees']:
    base.append(element.split(' ')[0])

if base > 31:
    count= count +1
else
    count2 = count2 +1

print(count)
print(count2)

输出应该告诉我count的值是2,而count2的值是1。问题是我无法比较float和list。我怎样才能使if起作用


Tags: 数据baseifcountelementjohnlistmark
1条回答
网友
1楼 · 发布于 2024-06-01 06:19:44

您有一个带有df列的Employees,需要将其拆分为数字和文本,保留数字并将其转换为浮点,然后根据值对其进行过滤:

import pandas as pd

df = pd.DataFrame({'Employees': ["122.12 (Mark/Jen)", "32.11(John/Albert)", 
                                 "29.1(Jo/Lian)"]})
print(df)

# split at (
df["value"] = df["Employees"].str.split("(") 

# convert to float
df["value"] =  pd.to_numeric(df["value"].str[0])

print(df)

# filter it into 2 series
smaller = df["value"] < 31
remainder = df["value"] > 30

print(smaller) 
print(remainder)


# counts 
smaller31 = sum(smaller)   # True == 1 -> sum([True,False,False]) == 1
bigger30 = sum(remainder)

print(f"Smaller: {smaller31}      bigger30: {bigger30}")

输出:

# df
            Employees   
0   122.12 (Mark/Jen)   
1  32.11(John/Albert)   
2       29.1(Jo/Lian)   

# after split/to_numeric
            Employees   value
0   122.12 (Mark/Jen)  122.12
1  32.11(John/Albert)   32.11
2       29.1(Jo/Lian)   29.10

# smaller
0    False
1    False
2     True
Name: value, dtype: bool

# remainder
0     True
1     True
2    False
Name: value, dtype: bool

# counted
Smaller: 1      bigger30: 2

相关问题 更多 >