pandas 将J/N替换为python中单个单元格的说明

xpcnnkqh  于 2023-01-19  发布在  Python
关注(0)|答案(2)|浏览(152)

在每一 Dataframe 的列的每一行中,I具有以下=(J,N,N,J,N)。
因此,它看起来如下所示:
| 姓名|选择|
| - ------|- ------|
| 亨克|日本、日本、日本、日本|
| 汤姆|N、J、N、N|
| 蒂姆|J、N、J、J|
我想为选择的第一个字母一个值geven。所以选择的Henk的第一个字母是'J'和汤姆是'N'。对于'J'我想说如果'J'比'新地址'如果'N'那么'旧地址'。对于第二个字母,对于Henk是"N",则我想给出其他值,例如对于"J",则为"新车",如果为"N",则为"旧车"。因此,对于Henk,将为"旧车"。等等。
我怎么能用python做到这一点呢?
产出
| 姓名|选择|解释|
| - ------|- ------|- ------|
| 亨克|日本、日本、日本、日本|新地址,旧车,旧城,新区|
| 汤姆|N、J、N、N|旧地址,新车,老城,旧区|
| 蒂姆|J、N、J、J|新地址,旧车,新城,新区|

4c8rllxm

4c8rllxm1#

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)
gmol1639

gmol16392#

试试看:

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

相关问题