Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在要素列上使用“应用”(或其他内容)创建多个要素列_Python_Pandas_Dataframe_Pandas Apply - Fatal编程技术网

Python 在要素列上使用“应用”(或其他内容)创建多个要素列

Python 在要素列上使用“应用”(或其他内容)创建多个要素列,python,pandas,dataframe,pandas-apply,Python,Pandas,Dataframe,Pandas Apply,我有一个数据帧: df = pd.DataFrame({'col1': [69, 77, 88], 'col2': ['barfoo', 'foo', 'bar']}) print(df) col1 col2 0 69 barfoo 1 77 foo 2 88 bar 我还有一个函数,它根据字符串返回两个值: def get_first_n_second(string): ''' Func

我有一个数据帧:

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

   col1    col2
0    69  barfoo
1    77     foo
2    88     bar 
我还有一个函数,它根据字符串返回两个值:

def get_first_n_second(string):
    '''
    Function returns two values for two columns
    '''
    value1 = string[0]
    value2 = string[1]
    return value1, value2
我想基于col2创建两个新列(它不起作用):

期望输出:

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

有两个更改-从函数返回系列:

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

有两个更改-从函数返回系列:

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
方法。使用内置函数可能比
更有效。应用

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

备选方案:使用内置的
str
方法。使用内置函数可能比
更有效。应用

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

是的,我提到了关于在完整数据帧上应用的错误。这是偶然的。@Warrior404-没问题;)是的,我提到了关于在完整数据帧上应用的错误。这是偶然的。@Warrior404-没问题;)在这种情况下,我认为您的解决方案更好、更简单,但在我的实际项目中有更复杂的功能。所以
str
方法没有这样的方法。不过还是谢谢你。在这种情况下,我认为你的解决方案更好更简单,但在我的实际项目中有更复杂的功能。所以
str
方法没有这样的方法。不过还是谢谢你。