简体   繁体   中英

Concatenating columns' string values depending on the condition in Pandas

I am concatenating three columns' values that are all formatted as str to be able to get the full address. The first one is the unit number, and some properties do not have a unit number, so I would like to not concatenate the unit number value for those where it's missing. How do I add the if statement?

df['address_original'] = df['unit_number'].str.cat(df[['street_number', 'street_name']], 
                                                   sep=', ')
print df['address_original'][:5]


0                 , 184, VEALE ROAD
1                 , 124, VEALE ROAD
2    , 1068, CLEARWATER VALLEY ROAD
3               , 1605, PINE STREET
4         , 1425, LOPEZ CREEK DRIVE
Name: address_original, dtype: object

Here's the original dataframe:

import pandas as pd
df = pd.DataFrame(data=search_results1)
print df.info()
print type(df)

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2619 entries, 0 to 2618
Columns: 111 entries, access to zoning
dtypes: object(111)
memory usage: 2.2+ MB
None

Here's currently what's in address_original column

print df['address_original'][:3]
0                 , 184, VEALE ROAD
1                 , 124, VEALE ROAD
2    , 1068, CLEARWATER VALLEY ROAD
Name: address_original, dtype: object

Is it then?

df['address_original'] = np.where(df['unit_number'].isnull(), df['street_number'].astype(str)+','+df['street_name'].astype(str), df['unit_Number'].astype(str)+','+df['street_number'].astype(str)+','+df['street_name'].astype(str))

I am still not sure how your target column should look like

Try this, may this helps you

import numpy as np
import pandas as pd


data = pd.read_csv('c.csv')
print(data)

def GetFullAddress(unitno, add1, add2):
    print(unitno, add1, add2)
    sunitno = ''
    if(unitno>0):
        sunitno = str(unitno)+', '

    return sunitno + add1 + ', '+add2

data['address'] = data.apply(lambda row: GetFullAddress(row['unitno'],row['add1'],row['add2']))
print(data)

Used data is:

   unitno         add1         add2
0       0  'address11'  'address21'
1      12  'address12'  'address22'
2       0  'address13'  'address23'
3      14  'address14'  'address24'
4       0  'address15'  'address25'

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