大熊猫申请一个新专栏

时间:2017-03-29 10:12:19

标签: python pandas

我有一个这样的数据框:

import pandas as pd
import numpy as np
df=pd.DataFrame({'c1':[1,2,4,5],
                'c2':[3,'P','N','T'],
                'c3':np.nan})

df

   c1   c2  c3
0   1   3   NaN
1   2   P   NaN
2   4   N   NaN
3   5   T   NaN

我想根据c3列更改c2值:

我想要的结果:

    c1  c2  c3
 0  1   3   NaN
 1  2   P   1.0
 2  4   N   3.0
 3  5   T   5.0

我使用concat来获得此结果:

df1=df[df.c2 == 'P']
df1['c3'] =1
df2=df[df.c2 == 'N']
df2['c3'] =3
df3=df[df.c2 == 'T']
df3['c3'] =5
df4=df[(df.c2 != 'N') & (df.c2 != 'P') & (df.c2 != 'T')]
new_df=pandas.concat([df1,df2,df3,df4]).reset_index()
new_df[['c1','c2','c3']]

我想使用apply函数来获得相同的结果。当我使用c3函数时,我总是替换整个apply列:

def new_col(x,df):

    if x== 'P':
        df['c3'] = 1
    elif x == 'N':
        df['c3'] = 3
    elif x == 'T':
        df['c3'] =5
    else:
        df['c3']=np.nan
df.c2.apply(new_col,df=df)
df

我如何更改new_col功能?

1 个答案:

答案 0 :(得分:1)

您可以使用:

def new_col(x):
    a = np.nan
    if x == 'P':
        a = 1
    elif x == 'N':
        a = 3
    elif x == 'T':
       a = 5
    return a

df['c3'] = df.c2.apply(new_col)
print (df)
   c1 c2   c3
0   1  3  NaN
1   2  P  1.0
2   4  N  3.0
3   5  T  5.0

另一种解决方案:

df.loc[df.c2 == 'P', 'C3'] = 1
df.loc[df.c2 == 'N', 'C3'] = 3
df.loc[df.c2 == 'T', 'C3'] = 5
print (df)
   c1 c2  c3   C3
0   1  3 NaN  NaN
1   2  P NaN  1.0
2   4  N NaN  3.0
3   5  T NaN  5.0