[英]How to edit all values of a column in a pandas dataframe?
I am trying to edit all the values in a specific column ( 'ISSN1'
) of a dataframe ( df1
) in pandas.我正在尝试编辑 pandas 中 dataframe ( df1
) 的特定列 ( 'ISSN1'
) 中的所有值。 An example value of this column is 1234-5678
and I would like it to be modified in order to remove the -
(thus obtaining 12345678
).此列的示例值为1234-5678
,我希望对其进行修改以删除-
(从而获得12345678
)。
If I do this:如果我这样做:
print(df1)
for elem in df1.ISSN1:
elem = str(elem).replace("-", "")
print(df1)
The dataframe results in being apparently unchanged and I get no error message. dataframe 结果显然没有改变,我没有收到错误消息。 Why?为什么? How can I remove the dash in all values of the 'ISSN1'
column?如何删除'ISSN1'
列的所有值中的破折号? Notice that some values are NaN
.请注意,某些值为NaN
。
I found some answers using lambdas but I find it a little confusing and since I am still learning I would prefer an answer that doesn't include lambdas.我找到了一些使用 lambdas 的答案,但我发现它有点令人困惑,因为我还在学习,我更喜欢不包含 lambdas 的答案。
You can use apply
:您可以使用apply
:
df1['ISSN1'] = df1['ISSN1'].apply(lambda x: str(x).replace('-', '')
Or pd.Series.str
method:或pd.Series.str
方法:
df1['ISSN1'] = df1['ISSN1'].astype(str).str.replace('-', '')
If your column contains only strings and possibly np.nan
you can remove astype(str)
:如果您的列仅包含字符串并且可能包含np.nan
您可以删除astype(str)
:
df1['ISSN1'] = df1['ISSN1'].str.replace('-', '')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.