Equivalent of Paste R to Python

后端 未结 8 773
忘掉有多难
忘掉有多难 2021-02-01 14:32

I am a new python afficionado. For R users, there is one function : paste that helps to concatenate two or more variables in a dataframe. It\'s very useful. For example Suppose

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-01 15:18

    my anwser is loosely based on original question, was edited from answer by woles. I would like to illustrate the points:

    • paste is % operator in python
    • using apply you can make new value and assign it to new column

    for R folks: there is no ifelse in direct form (but there are ways to nicely replace it).

    import numpy as np
    import pandas as pd
    
    dates = pd.date_range('20140412',periods=7)
    df = pd.DataFrame(np.random.randn(7,4),index=dates,columns=list('ABCD'))
    df['categorie'] = ['z', 'z', 'l', 'l', 'e', 'e', 'p']
    
    def apply_to_row(x):
        ret = "this is the value i want: %f" % x['A']
        if x['B'] > 0:
            ret = "no, this one is better: %f" % x['C']
        return ret
    
    df['theColumnIWant'] = df.apply(apply_to_row, axis = 1)
    print df
    

提交回复
热议问题