[英]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.