python - 如何根据现有列 Pandas 的多个条件创建新列

标签 python python-3.x pandas list-comprehension

所以我有一个包含 9 位 ID 的 df 列。没有重复项,每个 ID 都以 1-6 范围内的不同数字开头——具体取决于每个 ID 开头的数字,我想创建一个单独的列,其中包含 ID 的第一个数字代表的“名称”。 (例如,以 1 开头的 ID 代表缅因州,以 2 开头的 ID 代表加利福尼亚州...等等)

如果只有两个条件,则此方法有效:

df['id_label'] = ['name_1' if name.startswith('1') else 'everything_else' for name in df['col_1']]

我不知道如何为我需要的内容创建多行行理解,所以我认为这可行,但它只从循环的最后一次迭代中创建 id_label 列(即 id_label 列将仅包含 'name_5):

for col in df['col_1']:
    if col.startswith('1'):
        df['id_label'] = 'name_1'
    if col.startswith('2'):
        df['id_label'] = 'name_2'
    if col.startswith('3'):
       df['id_label'] = 'name_3'
    if col.startswith('4'):
        df['id_label'] = 'name_4'
    if col.startswith('5'):
        df['id_label'] = 'name_5'
    if col.startswith('6'):
        df['id_label'] = 'name_5'

我的问题是如何根据多个条件语句从旧列创建新列?

最佳答案

如果有很多 if else,可以使用 apply

def ifef(col):
    col = str(col)
    if col.startswith('1'):
        return  'name_1'
    if col.startswith('2'):
        return 'name_2'
    if col.startswith('3'):
        return 'name_3'
    if col.startswith('4'):
        return'name_4'
    if col.startswith('5'):
        return 'name_5'
    if col.startswith('6'):
        return 'name_5'
df = pd.DataFrame({'col_1':[133,255,36,477,55,63]})
df['id_label'] = df['col_1'].apply(ifef)
   col_1 id_label
0    133   name_1
1    255   name_2
2     36   name_3
3    477   name_4
4     55   name_5
5     63   name_5

In case if you have a dictionaary you can use

df = pd.DataFrame({'col_1':[133,255,36,477,55,63]})
d = {'1':'M', '2': 'C', '3':'a', '4':'f', '5':'r', '6':'s'}
def ifef(col):
    col = str(col)
    return d[col[0]]

df['id_label'] = df['col_1'].apply(ifef)
print(df)
  col_1 id_label
0    133        M
1    255        C
2     36        a
3    477        f
4     55        r
5     63        s

关于python - 如何根据现有列 Pandas 的多个条件创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45107555/

相关文章:

python - 加权平均日期时间,关闭但仅限某些月份

python - 是什么导致了这个程序的错误

python - 合并 Pandas Dataframes 时如何仅使用第一个匹配项?

python - 使用 sympy 解析字符串时出现意外行为

python - 返回 header cgi 之前脚本超时

Python 文件创建日期和重命名 - 请求批评

python - Click支持 "bunching"做空期权吗?

python - 如何使用 mask 更改图像的颜色?

python - 无法从以元组为列的字典中创建具有 MultiIndex 列的 pandas DataFrame

python - 在 numpy/pandas 中用组聚合替换组的值