【问题标题】:Divide dataframe into two sets according to a column根据列将数据框分为两组
【发布时间】:2017-05-15 21:48:11
【问题描述】:

我有 Dataframe df 我选择了其中的一些库,我想根据名为 Sevrice 的库将它们分为 xtrain 和 xtest。这样将带有 1 和 o 的原始数据放入 xtrain 并将 nan 放入 xtest。

Service
1
0
0
1
Nan
Nan

xtarin = df.loc[df['Service'].notnull(), ['Age','Fare', 'GSize','Deck','Class', 'Profession_title' ]]

已编辑

    ytrain = df['Service'].dropna()
    Xtest=df.loc[df['Service'].isnull(),['Age','Fare','GSize','Deck','Class','Profession_title']]
    import pandas as pd
    from sklearn.linear_model import LogisticRegression
    logistic = LogisticRegression()
    logistic.fit(xtrain, ytrain)
    logistic.predict(xtest)

logistic.predict(xtest) 出现此错误

X has 220 features per sample; expecting 307

【问题讨论】:

    标签: python pandas logistic-regression sklearn-pandas


    【解决方案1】:

    我觉得你需要isnull:

    Xtest=df.loc[df['Service'].isnull(),['Age','Fare','GSize','Deck','Class','Profession_title']]
    

    另一种解决方案是将boolean mask 反转为~

    mask = df['Service'].notnull()
    xtarin = df.loc[mask, ['Age','Fare', 'GSize','Deck','Class', 'Profession_title' ]]
    Xtest = df.loc[~mask, ['Age','Fare', 'GSize','Deck','Class', 'Profession_title' ]]
    

    编辑:

    df = pd.DataFrame({'Service':[1,0,np.nan,np.nan],
                       'Age':[4,5,6,5],
                       'Fare':[7,8,9,5],
                       'GSize':[1,3,5,7],
                       'Deck':[5,3,6,2],
                       'Class':[7,4,3,0],
                        'Profession_title':[6,7,4,6]})
    
    print (df)
       Age  Class  Deck  Fare  GSize  Profession_title  Service
    0    4      7     5     7      1                 6      1.0
    1    5      4     3     8      3                 7      0.0
    2    6      3     6     9      5                 4      NaN
    3    5      0     2     5      7                 6      NaN
    
    ytrain = df['Service'].dropna()
    xtrain = df.loc[df['Service'].notnull(), ['Age','Fare', 'GSize','Deck','Class', 'Profession_title' ]]
    xtest=df.loc[df['Service'].isnull(),['Age','Fare','GSize','Deck','Class','Profession_title']]
    import pandas as pd
    from sklearn.linear_model import LogisticRegression
    logistic = LogisticRegression()
    logistic.fit(xtrain, ytrain)
    print (logistic.predict(xtest))
    [ 0.  0.]
    

    【讨论】:

    • 谢谢,您知道我为什么会收到此错误吗? X 每个样本有 220 个特征;预计 307
    • 数据似乎有问题,我用一些样本测试它,它可以工作,见编辑。
    • 感谢您的接受。我用你的 csv 和同样的问题尝试你的代码。问题是xtrainxtest 的列长度不同,print (xtrain.info()) print (xtest.info())
    • 解决方案是xtest = xtest.reindex(columns=xtrain.columns, fill_value=0) print(logistic.predict(xtest))
    • reindex by columns, if NaN get 0 - 所以这段代码将所有缺失的列添加到xtest并用0填充它们
    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2019-09-15
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    相关资源
    最近更新 更多