简体   繁体   中英

python pandas dataframe: transform a column and append it to the end

I have the following code, trying to transform column v2, and add a new column:

df = pd.read_csv('test1.csv')
for index, row in df.iterrows():
    v4 = myFunction.classify(row['v2'])
    row['v4'] = v4
    row.append(v4)

However, the line row.append(v4) doesn't work. What would be a proper way to get v4 append to each row? Thanks!

Currently, the df looks like:

   v1      v2  v3  result
0  12     Dog  31       0
1  34    Frog   4       1
2  32   Snake   5       1
3   7     Cat   2       0

and the expected new df should be:

   v1      v2  v3  result   v4
0  12     Dog  31       0   Mammal
1  34   Eagle   4       1   Bird
2  32   Snake   5       1   Reptile
3   7     Cat   2       0   Mammal

Can your function accept a column and output a column? If so you do not need to iterate over your df. Just pass in a column and assign the output to v4.

v4 = myFunction.classify(df['v2'])
df['v4'] = v4

If you function needs individual input then create the column 'v4' first and then replace values you iterate over rows. Again, you would not need append here.

Another option in the individual input case would be to use the python built-in map() to apply your function to the entire column of df['v2'] and then assign that output as above.

df['v4'] = map(myFunction.classify, df['v2'])

尝试了几种方法,我相信迄今为止最好的方法如下:

df['v4'] = df['v2'].apply(myFunction.classify)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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