用python中单个单元格中的解释替换J/N



在每个数据帧的列的每一行中我有如下的= (J,N,N,J,N)

所以它看起来像这样:

<表类> 名称 选择 tbody><<tr>HenkJ N, N, J汤姆N, N, N蒂姆J, N, J,
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)

尝试:

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)

打印:

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

最新更新