温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - applying a function to all the entries from a ; delimited column (map? pandas?)
pandas python

python - 将函数应用于来自的所有条目;

发布于 2020-03-27 15:38:58

我有以下数据框,并希望替换第三列的值(定界符=“;”)。

cat file.text

Name         ID        Values
John         81-502    1
Mike         81-501    2;2;2
Matthew      81-512    1,0
def fun(x):
     return x+1

我想应用此函数来替换数据框中的“值”列,以便:

cat out.txt

Name         ID        Values
John         81-502    2
Mike         81-501    3;3;3
Matthew      81-512    2;1

查看更多

查看更多

提问者
user171558
被浏览
15
jezrael 2020-01-31 16:24

首先是必要的split值,将其转换为整数,将add 1,转换为字符串并通过;以下方式加入

df['Values'] = df['Values'].apply(lambda x: ';'.join(str(int(y) + 1) for y in x.split(';')))

列表理解的解决方案:

df['Values'] = [ ';'.join(str(int(y) + 1) for y in x.split(';')) for x in df['Values']]

print (df)
      Name      ID Values
0     John  81-502      2
1     Mike  81-501  3;3;3
2  Matthew  81-512    2;1