[英]Create new dataframe column based on a specific character of a string in another column, pandas
I have a dataframe with a column that contain strings.我有一个 dataframe ,其中有一列包含字符串。 I want to know if it is possible to create a new column based on the dataframe.
我想知道是否可以基于 dataframe 创建一个新列。 This is an example of the column:
这是该列的示例:
col1
016e3d588c
071b4x718g
011e3d598c
041e0i608g
I want to create a new column based on the last character of the string.我想根据字符串的最后一个字符创建一个新列。 This is what I tried:
这是我尝试过的:
for i in DF['col1']:
if i[-1] == 'g':
DF['col2'] = 1
else:
DF['col2'] = 0
I want the new column like this:我想要这样的新专栏:
col2
0
1
0
1
but my code have the following output:但我的代码有以下 output:
col2
0
0
0
0
Is possible to do it?有可能做到吗?
Thanks in advance提前致谢
Using str.endswith()
使用
str.endswith()
Ex:前任:
df = pd.DataFrame({"Col1": ['016e3d588c', '071b4x718g', '011e3d598c', '041e0i608g']})
df["Col2"] = df["Col1"].str.endswith("g").astype(int)
print(df)
Output: Output:
Col1 Col2
0 016e3d588c 0
1 071b4x718g 1
2 011e3d598c 0
3 041e0i608g 1
You can try this using numpy
.您可以使用
numpy
尝试此操作。
import numpy as np
DF["col2"] = np.where(DF["col1"].str[-1]=="g",1,0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.