Python pandas-基于其他列的新列(字符串)

时间:2019-09-19 17:35:18

标签: python pandas

我在stackoverflow中找不到它,所以我想问这个问题。

让我们假设我有两列:数据框中的A,B,它仅由一堆单词组成,并且我想根据以下规则创建一个新的C列,它是TRUE / FALSE:

 If word in B = word in A + 'ing', then it's True or vice versa
 If word in B = word in A + 'ment', then it's True of vice versa. 

所以我定义了以下函数:

def parts_of_speech(s1, s2):
    return s1+'ing'==s2 or s1+'ment'==s2 or s1+s1[-1]+'ing'==s2

例如

  A              B            C
Engage         Engagement   True
Go             Going        True
Axe            Axis         False
Management     Manage       True

我尝试了以下操作:

df['C']=df.apply(lambda x: parts_of_speech(x.A, x.B) or 
                           parts_of_speech(x.B, x.A) )

df['C']=df.apply(parts_of_speech(df['A'], df['B']) or 
                           parts_of_speech(df['A'], df['B']) )

我遇到相同的错误:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

我不知道我做错了什么。有一个简单的解决方法吗?

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

.apply默认情况下适用于列。您的示例中唯一需要做的更改是添加str(int(bin(str(stringofOandI)))) 以应用于行:

axis=1

答案 1 :(得分:1)

获取示例数据:

# make B the longer words
df[['A','B']] = np.sort(df[['A','B']])

# split by suffixes
df['B'].str.extract('(\w+)(ment|ing)$',expand=True)[0].eq(df['A'])

或者使用您的方法,但将其向量化:

# make B the longer words
df[['A','B']] = np.sort(df[['A','B']])

df['A-ing'] = df['A'] + 'ing'
df['A-ment'] = df['A'] + 'ment'

df.iloc[:,-2].eq(df['A']).all(1)

输出:

0     True
1     True
2    False
3     True
dtype: bool