无法从帧中检索数据

时间:2017-07-31 10:56:36

标签: python-3.x jupyter-notebook data-science

我正在尝试从具有特定条件的数据帧中检索特定数据,但它显示空数据帧。我是数据科学的新手,正在努力学习数据科学。这是我的代码。

file = open('/home/jeet/files1/files/ch03/adult.data', 'r')
def chr_int(a):
    if a.isdigit(): return int(a)
    else: return 0

data = []
for line in file:
    data1 = line.split(',')
    if len(data1) == 15:
        data.append([chr_int(data1[0]), data1[1],
                   chr_int(data1[2]), data1[3],
                   chr_int(data1[4]), data1[5],
                   data1[6], data1[7], data1[8],
                   data1[9], chr_int(data1[10]),
                   chr_int(data1[11]),
                   chr_int(data1[12]),
                   data1[13], data1[14]])

import pandas as pd
df = pd.DataFrame(data)
df.columns = ['age', 'type-employer', 'fnlwgt', 'education','education_num', 'marital','occupation', 'relationship','race','sex','capital_gain','capital_loss','hr_per_week','country','income']

ml = df[(df.sex == 'Male')] # here i retrive data who is male
ml1 = df[(df.sex == 'Male') & (df.income == '>50K\n')]
print(ml1.head()) # here i printing that data
fm =df[(df.sex == 'Female')]
fm1 = df [(df.sex == 'Female') & (df.income =='>50K\n')]

输出:

Empty DataFrame
Columns: [age, type-employer, fnlwgt, education, education_num, marital, occupation, relationship, race, sex, capital_gain, capital_loss, hr_per_week, country, income]
Index: []

代码有什么问题。为什么数据框是空的。

1 个答案:

答案 0 :(得分:0)

如果仔细检查值,可能会发现问题:

print(df.income.unique())
>>> [' <=50K\n' ' >50K\n']

每个值前面都有空格。因此,应该处理这些值以消除这些空格,或者应该像这样修改代码:

ml1 = df[(df.sex == 'Male') & (df.income == ' >50K\n')]
fm1 = df [(df.sex == 'Female') & (df.income ==' <=50K\n')]