在 pandas 列上使用应用(或其他方式)创建多个特征列

Creating multiple feature-columns using apply (or something else) on pandas column

我有一个数据框:

df = pd.DataFrame({'col1': [69, 77, 88],
                   'col2': ['barfoo', 'foo', 'bar']})
print(df)

   col1    col2
0    69  barfoo
1    77     foo
2    88     bar 

我也有 returns 两个基于字符串的值的函数:

def get_first_n_second(string):
    '''
    Function returns two values for two columns
    '''
    value1 = string[0]
    value2 = string[1]
    return value1, value2

我想基于 col2 创建两个新列(它不起作用):

df[['first', 'second']] = df['col2'].apply(get_first_n_second)

期望的输出:

   col1    col2   first   second
0    69  barfoo       b        a
1    77     foo       f        o
2    88     bar       b        a

有 2 处更改 - return Series 来自函数:

def get_first_n_second(string):
    '''
    Function returns two values for two columns
    '''
    value1 = string[0]
    value2 = string[1]
    return pd.Series([value1, value2])


df[['first', 'second']] = df['col2'].apply(get_first_n_second)
print (df)
   col1    col2 first second
0    69  barfoo     b      a
1    77     foo     f      o
2    88     bar     b      a

备选方案:使用内置的 str 方法。使用内置函数可能(?)比 .apply:

更有效
df['first'] = df['col2'].str[0]
df['second'] = df['col2'].str[1]