In each row of the column of een dataframe I have the following = (J,N,N,J,N).
So it looks like the following:
Name | Choices |
---|---|
Henk | J,N,N,J |
Tom | N,J,N,N |
Tim | J,N,J,J |
I would like for the first letter of the choice a value geven. So the first letter of Henk of the choice of Henk is 'J' and of Tom is 'N'. For 'J' I wand to say if 'J' than 'New address' if 'N' then 'Old address'. For the second letter, for Henk is 'N' than i want to give other value for example for 'J' then 'New car' and if 'N' then 'Old car'. So for Henk will be 'Old car'. And so on..
How can i do this with python?
Output
Name | Choices | Explanation |
---|---|---|
Henk | J,N,N,J | New address, Old car, Old city, New area |
Tom | N,J,N,N | Old address, New car, Old city, Old area |
Tim | J,N,J,J | New address, Old car, New city, New area |
CodePudding user response:
import pandas as pd
# initialize list of lists
data = [['Hank', 'J,N,N,J'], ['Tom', 'N,J,J,N'], ['Tim', 'J,N,J,J']]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Choices'])
df['address'] = df['Choices'].astype(str).str[0]
df['car'] = df['Choices'].astype(str).str[2]
df['city'] = df['Choices'].astype(str).str[4]
df['area'] = df['Choices'].astype(str).str[6]
df1 = df.iloc[:,2:6]
for i in df1:
df[i] = df[i].str.replace("N" , "Old " str(i))
df[i] = df[i].str.replace("J" , "New " str(i))
df["Explanation"] = df[['address', 'city', 'area', 'car']].agg(','.join, axis=1)
df = df.drop('address', axis=1)
df = df.drop('car', axis=1)
df = df.drop('city', axis=1)
df = df.drop('area', axis=1)
CodePudding user response:
Try:
mappings = [
{"J": "New address", "N": "Old address"},
{"J": "New car", "N": "Old car"},
{"J": "New city", "N": "Old city"},
{"J": "New area", "N": "Old area"},
]
df["Explanation"] = df.apply(
lambda x: ",".join(
mappings[i][ch] for i, ch in enumerate(map(str.strip, x["Choices"].split(",")))
),
axis=1,
)
print(df)
Prints:
Name Choices Explanation
0 Henk J,N,N,J New address,Old car,Old city,New area
1 Tom N,J,N,N Old address,New car,Old city,Old area
2 Tim J,N,J,J New address,Old car,New city,New area