使用多个条件在数据框中创建列

时间:2018-07-28 03:49:32

标签: python pandas

我正在尝试使用基于数据框中其他信息的多个条件语句在Pandas数据框中创建新列。我尝试使用.iteritems()进行迭代。此方法有效,但看起来不太优雅,并返回一条我不知道如何理解和/或纠正的通知。

我的代码段是:

proj_file_pq['pd_pq'] = 0

for key, value in proj_file_pq['pd_pq'].iteritems():

    if proj_file_pq['qualifying'].iloc[key] - \
        proj_file_pq['avg_pd'].iloc[key] < 1:
        proj_file_pq['pd_pq'].iloc[key] = \
            proj_file_pq['qualifying'].iloc[key] - 1

    elif proj_file_pq['qualifying'].iloc[key] > \
        proj_file_pq['avg_start'].iloc[key]:
        proj_file_pq['pd_pq'].iloc[key] = \
            proj_file_pq['qualifying'].iloc[key] - \
                proj_file_pq['avg_finish'].iloc[key]

    elif proj_file_pq['qualifying'].iloc[key] + \
        proj_file_pq['avg_pd'].iloc[key] > 40:
        proj_file_pq['pd_pq'].iloc[key] = \
            40 - proj_file_pq['qualifying'].iloc[key]

    else:
        proj_file_pq['pd_pq'].iloc[key] = proj_file_pq['avg_pd'].iloc[key]

print(proj_file_pq[['Driver', 'avg_start', 'avg_finish', 'qualifying',\
                     'avg_pd', 'pd_pq']].head())

这是结果输出:

C:\Python36\lib\site-packages\pandas\core\indexing.py:189: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)
              Driver  avg_start  avg_finish  qualifying  avg_pd  pd_pq
0  A.J. Allmendinger     18.000      21.875          16   3.875  3.875
1        Alex Bowman     14.500      18.000           8   3.500  3.500
2      Aric Almirola     21.250      19.250          13  -2.000 -2.000
3      Austin Dillon     18.875      18.375          17  -0.500 -0.500
4        B.J. McLeod     33.500      33.500          36   0.000  2.500

原始数据框具有以下标题:

{'Driver': {0: 'A.J. Allmendinger', 1: 'Alex Bowman', 2: 'Aric Almirola', 3: 'Austin Dillon', 4: 'B.J. McLeod'}, 'qualifying': {0: 16, 1: 8, 2: 13, 3: 17, 4: 36}, 'races': {0: 8, 1: 6, 2: 8, 3: 8, 4: 2}, 'avg_start': {0: 18.0, 1: 14.5, 2: 21.25, 3: 18.875, 4: 33.5}, 'avg_finish': {0: 21.875, 1: 18.0, 2: 19.25, 3: 18.375, 4: 33.5}, 'avg_pd': {0: 3.875, 1: 3.5, 2: -2.0, 3: -0.5, 4: 0.0}, 'percent_fl': {0: 0.0036250647332988096, 1: 0.0071770334928229675, 2: 0.03655483224837256, 3: 0.006718346253229974, 4: 0.0}, 'percent_ll': {0: 0.0031071983428275505, 1: 0.001594896331738437, 2: 0.03505257886830245, 3: 0.006718346253229974, 4: 0.0}, 'percent_lc': {0: 0.9587884806355512, 1: 0.6226415094339622, 2: 0.9915590863952334, 3: 0.9607745779543198, 4: 0.2398212512413108}, 'finish_rank': {0: 25.0, 1: 17.0, 2: 20.5, 3: 19.0, 4: 35.0}, 'pd_rank': {0: 7.0, 1: 9.0, 2: 26.0, 3: 23.0, 4: 19.5}, 'fl_rank': {0: 28.0, 1: 21.0, 2: 8.0, 3: 22.0, 4: 35.0}, 'll_rank': {0: 19.0, 1: 24.0, 2: 6.0, 3: 16.0, 4: 31.0}, 'overall': {0: 79.0, 1: 71.0, 2: 60.5, 3: 80.0, 4: 120.5}, 'overall_rank': {0: 22.0, 1: 20.0, 2: 13.0, 3: 24.0, 4: 34.0}, 'pd_pts': {0: 3.875, 1: 3.5, 2: -2.0, 3: -0.5, 4: 0.0}, 'fl_pts': {0: 0.5455722423614707, 1: 1.0801435406698563, 2: 5.50150225338007, 3: 1.0111111111111108, 4: 0.0}, 'll_pts': {0: 0.2338166752977732, 1: 0.12001594896331738, 2: 2.6377065598397595, 3: 0.5055555555555555, 4: 0.0}, 'finish_pts': {0: 22.0, 1: 30.0, 2: 26.5, 3: 28.0, 4: 12.0}, 'total_pts': {0: 26.654388917659244, 1: 34.70015948963317, 2: 32.63920881321983, 3: 29.016666666666666, 4: 12.0}}

感谢您提供改进建议。

3 个答案:

答案 0 :(得分:1)

我没有运行此程序,因为我没有测试数据,但这应该可以工作,假设我对括号是正确的,并且您将numpy导入为np

将numpy导入为np

proj_file_pq['pd_pq'] = np.where(proj_file_pq['qualifying'] - proj_file_pq['avg_pd'] < 1, proj_file_pq['qualifying'] - 1, 
  np.where(proj_file_pq['qualifying'] > proj_file_pq['avg_start'], proj_file_pq['qualifying'] - proj_file_pq['avg_finish'], 
  np.where(proj_file_pq['qualifying'] + proj_file_pq['avg_pd'] > 40, 40 - proj_file_pq['qualifying'], 
  proj_file_pq['avg_pd']))

print(proj_file_pq[['Driver', 'avg_start', 'avg_finish', 'qualifying',\
                 'avg_pd', 'pd_pq']].head())

您无需先创建proj_file_pq ['pd_pq']并使用此方法将其设置为0

答案 1 :(得分:1)

设置您的条件:

$('.addbutton').click(function() {
            var newItem = $('#new').val(),
                newLi = $('<li class="card"><label><input type="checkbox" /> '+newItem+ ' <p>Due Date: <input class="datepicker" type="text" placeholder="MM/DD/YYYY" /></p></li>');

            $(this).closest('div.container').find('ul').append(newLi);
            newLi.find('.datepicker').datepicker();
        });

以及您相应的输出:

c1 = (df.qualifying - df.avg_pd).lt(1)
c2 = (df.qualifying.gt(df.avg_start))
c3 = (df.qualifying.add(df.avg_pd).gt(40))

使用 o1 = df.qualifying.sub(1) o2 = df.qualifying.sub(df.avg_finish) o3 = 40 - df.qualifying

np.select

答案 2 :(得分:1)

我要给你一个提示,就是错误:C:\Python36\lib\site-packages\pandas\core\indexing.py:189: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

在我创建多个数据框而未在命令末尾使用reset_index()创建数据框的情况下,通常会发生这种情况。您可能想在创建表时使用它来查看它是否摆脱了切片错误。如果您已经有一个ID列,那么通常会使用reset_index(drop=True)以避免创建多余的ID列。

我希望这可以解决这个问题!