对于特定的列(dtype = object),如果字符串以'-‘结尾,那么如何将'-’添加到字符串的开头。
即皈依:“May500 500-”to -5月500
(我需要将它添加到列中的每个元素中)
发布于 2021-03-25 03:07:51
def add_prefix(text):
# If text is null or empty string the -1 index will result in IndexError
if text and text[-1] == "-":
return "-"+text
return text
df = pd.DataFrame(data={'A':["MAY500", "MAY500-", "", None, np.nan]})
# Change the column to string dtype first
df['A'] = df['A'].astype(str)
df['A'] = df['A'].apply(add_prefix)
0 MAY500
1 -MAY500-
2
3 None
4 nan
Name: A, dtype: object
发布于 2021-03-25 03:14:01
试着做这样的事情:
#setup
df = pd.DataFrame({'col':['aaaa','bbbb-','cc-','dddddddd-']})
mask = df.col.str.endswith('-'), 'col'
df.loc[mask] = '-' + df.loc[mask]
输出
df
col
0 aaaa
1 -bbbb-
2 -cc-
3 -dddddddd-
发布于 2021-03-25 03:15:22
您可以使用np.select
给出如下数据:
df
values
0 abcd-
1 a-bcd
2 efg-
您可以按以下方式使用np.select
:
df['values'] = np.select([df['values'].str.endswith('-')], ['-' + df['values']], df['values'])
产出:
df
values
0 -abcd-
1 a-bcd
2 -efg-
https://stackoverflow.com/questions/66792372
复制相似问题