Python 熊猫:从以字符结尾的现有列创建新列

Python 熊猫:从以字符结尾的现有列创建新列,python,pandas,Python,Pandas,我需要从这个数据框中选择多个以['edit']结尾的字符串,使新列名为'state'。这应该可以: df['state'] = df.loc[df['YourCol'].str.endswith('[edit]'), 'YourCol'] 只需将您的col替换为您正在使用的列,将df替换为您的数据帧的名称。请注意,如果不以[edit]结尾,您将得到NaN值。我认为您尝试使用[edit]行,而不仅仅是作为单独的列,而是将它们映射到它们下面的学校,这样您将得到如下结果: School

我需要从这个数据框中选择多个以['edit']结尾的字符串,使新列名为'state'。

这应该可以:

df['state'] = df.loc[df['YourCol'].str.endswith('[edit]'), 'YourCol']

只需将您的col替换为您正在使用的列,将df替换为您的数据帧的名称。请注意,如果不以[edit]结尾,您将得到NaN值。

我认为您尝试使用[edit]行,而不仅仅是作为单独的列,而是将它们映射到它们下面的学校,这样您将得到如下结果:

School                                           State

Fairbanks (University of Alaska Fairbanks)[2]    Alaska
Flagstaff (Northern Arizona University)          Arizona
Tempe (Arizona State University)                 Arizona
Tucson (University of Arizona)                   Arizona
Arkadelphia (Henderson State University, ...)    Arkansas
如果是这样,你可以将尼古拉斯·热尔韦的答案与熊猫的答案结合起来:


请提供一个答案。到底是什么问题?你试过什么,做过什么研究吗?堆栈溢出不是免费的代码编写服务。见:。
df['State'] = df[df['YourCol'].str.endswith('[edit]')]['YourCol']
df['State'] = df['State'].fillna(method='ffill') # Forward-fills the states
df = df.drop(df[df['YourCol'].str.endswith('[edit]')]) # Drop the "header" rows
df['State'] = df['State'].str.slice_replace(start=-6) # Remove "[edit]" from the end of the state names