简体   繁体   English

根据另一列中字符串的特定字符 pandas 创建新的 dataframe 列

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

相关问题 检查特定列是否大于另一列并根据 pandas dataframe 中的条件创建新列 - Check if specific column is greater than another column and create a new column based on condition in pandas dataframe 如何基于另一个DataFrame中的列在Pandas DataFrame中创建新列? - How to create a new column in a Pandas DataFrame based on a column in another DataFrame? 根据另一列中的“NaN”值在 Pandas Dataframe 中创建一个新列 - Create a new column in Pandas Dataframe based on the 'NaN' values in another column Pandas 数据框根据另一列的条件创建新行 - Pandas dataframe create new rows based on condition from another column Pandas 根据来自另一个 dataframe 的计数和条件创建新列 - Pandas Create new column based on a count and a condition from another dataframe 基于在DataFrame中找到的字符串的Pandas New Column - Pandas New Column based on found string in a DataFrame 基于数据框的其他列创建一个新的熊猫数据框列 - Create a new pandas dataframe column based on other column of the dataframe 根据另一列的字符串创建一个新列 - create a new column based on string of another column Pandas:根据 DataFrame 中的其他列在 DataFrame 中创建新列 - Pandas: Create new column in DataFrame based on other column in DataFrame 根据来自另一个熊猫数据框的列在熊猫数据框中创建新行 - Create new rows in a Pandas Dataframe based on a column from another pandas dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM