简体   繁体   中英

Concatenation in Pandas-Python

I've a pandas data frame in which I want to get values from a column and concatenate them only if the date column and No. column of those entries match. Here is the sample of the data table

No. Date       Code
121 1-Jul-15    AT
122 2-Jul-17    PN
122 2-Jul-17    WX
122 3-Jul-17    FX

The output should be like this

No. Date       Code Output
121 1-Jul-15    AT  AT
122 2-Jul-17    PN  PN/WX
122 2-Jul-17    WX  PN/WX
122 3-Jul-17    FX  FX

I've nearly 172355 rows that I want this operation to happen on.

This is a basic pseudo code I tried

for i in 1 to len(df)
    if date & no is same
        concatenate code to new column of only same rows
    else
        copy code to new column as it is 
i = i+1
end for

Kindly help me getting this output with the python code in pandas.

I believe you need transform for new column in original DataFrame :

df['new'] = df.groupby(['No.','Date'])['Code'].transform('/'.join)
print (df)
   No.      Date Code    new
0  121  1-Jul-15   AT     AT
1  122  2-Jul-17   PN  PN/WX
2  122  2-Jul-17   WX  PN/WX
3  122  3-Jul-17   FX     FX

Because if use apply then output is aggregated:

df1 = df.groupby(['No.','Date'])['Code'].apply('/'.join).reset_index(name='new')
print (df1)
   No.      Date    new
0  121  1-Jul-15     AT
1  122  2-Jul-17  PN/WX
2  122  3-Jul-17     FX

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