'Getting "AttributeError: Can only use .str accessor with string values" while transposing the data in dataframe
I have one source file with structure as below:
ID|RcrdId|SrcId|Name|Address
row1|r1|src1#src2|val1#val2|val4#val5
row2|r2|src2#src1|val11#val12|val14#val15
row3|r3|src1|val44|val23
I need to include values in Name and Address fields only for Src2 value which is present in SrcID column, in case there is no value for SRC2, then null values should be populated in the Name and address field like below(RecordID=r3):
ID|RcrdId|SrcId|Name|Address
row1|r1|src2|val2|val5
row2|r2|src2|val11|val14
row3|r3|||
I have this sample code, but I am not able to handle the record r3 where src2 is not present and I am getting following error : AttributeError: Can only use .str accessor with string values!
from itertools import zip_longest
cols = ['SrcId', 'Name', 'Address']
df[cols] = (df[cols].fillna(#)
.apply(lambda c: c.str.split('#'))
.apply(lambda r: next(filter(lambda x: x[0]=='src2',
zip_longest(*r)), float('nan')),
axis=1, result_type='expand')
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
