![](/img/trans.png)
[英]Check if specific column is greater than another column and create a new column based on condition in pandas dataframe
[英]Create new dataframe column based on a specific character of a string in another column, pandas
我有一个 dataframe ,其中有一列包含字符串。 我想知道是否可以基于 dataframe 创建一个新列。 这是该列的示例:
col1
016e3d588c
071b4x718g
011e3d598c
041e0i608g
我想根据字符串的最后一个字符创建一个新列。 这是我尝试过的:
for i in DF['col1']:
if i[-1] == 'g':
DF['col2'] = 1
else:
DF['col2'] = 0
我想要这样的新专栏:
col2
0
1
0
1
但我的代码有以下 output:
col2
0
0
0
0
有可能做到吗?
提前致谢
使用str.endswith()
前任:
df = pd.DataFrame({"Col1": ['016e3d588c', '071b4x718g', '011e3d598c', '041e0i608g']})
df["Col2"] = df["Col1"].str.endswith("g").astype(int)
print(df)
Output:
Col1 Col2
0 016e3d588c 0
1 071b4x718g 1
2 011e3d598c 0
3 041e0i608g 1
您可以使用numpy
尝试此操作。
import numpy as np
DF["col2"] = np.where(DF["col1"].str[-1]=="g",1,0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.