繁体   English   中英

Python:根据if语句条件填充新的df列

[英]Python: Populate new df column based on if statement condition

我正在尝试新的东西。 我想根据影响具有值的另一列的某些条件填充新的 df 列。

我有一个包含两列(ID,零售商)的数据框。 我想根据 ID 列中的 ID 填充零售商列。 我知道如何在 SQL 中使用 CASE 语句执行此操作,但是如何在 python 中执行此操作?

我看过这个例子,但它不是我正在寻找的。

Python:使用 if/else 语句填充新列

import pandas as pd

data = {'ID':['112','5898','32','9985','23','577','17','200','156']}

df = pd.DataFrame(data)

df['Retailer']=''

if df['ID'] in (112,32):
    df['Retailer']='Webmania'
elif df['ID'] in (5898):
    df['Retailer']='DataHub'
elif df['ID'] in (9985):
    df['Retailer']='TorrentJunkie'
elif df['ID'] in (23):
    df['Retailer']='Apptronix'
else: df['Retailer']='Other'


print(df)

我期望看到的输出是这样的:

     ID Retailer
0   112 Webmania
1  5898 DataHub
2    32 Webmania
3  9985 TorrentJunkie
4    23 Apptronix
5   577 Other
6    17 Other
7   200 Other
8   156 Other

使用numpy.select和测试多个值使用Series.isin ,也如需要测试串像样本数据改变号码的数字像112'112'

m1 = df['ID'].isin(['112','32'])
m2 =  df['ID'] == '5898'
m3 =  df['ID'] == '9985'
m4 =  df['ID'] == '23'
vals = ['Webmania', 'DataHub', 'TorrentJunkie', 'Apptronix']
masks = [m1, m2, m3, m4]

df['Retailer'] = np.select(masks, vals, default='Other')
print(df)

     ID       Retailer
0   112       Webmania
1  5898        DataHub
2    32       Webmania
3  9985  TorrentJunkie
4    23      Apptronix
5   577          Other
6    17          Other
7   200          Other
8   156          Other

如果许多类别也可以使用具有自定义功能的解决方案:

def get_data(x):
    if x in ('112','32'):
        return 'Webmania'
    elif x == '5898':
        return 'DataHub'
    elif x == '9985':
        return 'TorrentJunkie'
    elif x == '23':
        return 'Apptronix'
    else: return 'Other'


df['Retailer'] =  df['ID'].apply(get_data)
print (df)
     ID       Retailer
0   112       Webmania
1  5898        DataHub
2    32       Webmania
3  9985  TorrentJunkie
4    23      Apptronix
5   577          Other
6    17          Other
7   200          Other
8   156          Other

或者按字典使用map ,如果没有匹配得到NaN ,所以添加了fillna

d = {'112': 'Webmania','32':'Webmania',
    '5898':'DataHub',
    '9985':'TorrentJunkie',
    '23':'Apptronix'}

df['Retailer'] =  df['ID'].map(d).fillna('Other')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM