简体   繁体   English

python pandas dataframe:转换一列并将其附加到末尾

[英]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:我有以下代码,尝试转换列 v2,并添加一个新列:

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.但是,行row.append(v4)不起作用。 What would be a proper way to get v4 append to each row?将 v4 附加到每一行的正确方法是什么? Thanks!谢谢!

Currently, the df looks like:目前,df 看起来像:

   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:并且预期的新 df 应该是:

   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.如果是这样,您不需要迭代您的 df。 Just pass in a column and assign the output to v4.只需传入一列并将输出分配给 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.如果您的函数需要单独的输入,则首先创建列“v4”,然后替换您在行上迭代的值。 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.单个输入情况下的另一个选择是使用 python 内置 map() 将您的函数应用于 df['v2'] 的整个列,然后如上所述分配该输出。

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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