Pandas 映射列的特定行

Pandas 映射列的特定行,pandas,Pandas,我试图在数据帧中映射一列的值,但仅当满足另一列的条件时才映射。要选择要映射的行,我只需使用.loc,然后将它们修改为: data = pd.DataFrame({'col_1': [1,2,2,3,1,2,3,2], 'col_2':[100, 'information/string', 'information/string', 4, 600, 'information/string', 7, 'information/string']}) relevant_rows = data.loc[

我试图在数据帧中映射一列的值,但仅当满足另一列的条件时才映射。要选择要映射的行,我只需使用.loc,然后将它们修改为:

data = pd.DataFrame({'col_1': [1,2,2,3,1,2,3,2], 'col_2':[100, 'information/string', 'information/string', 4, 600, 'information/string', 7, 'information/string']})

relevant_rows = data.loc[data['col_1']==2]
relevant_rows = data.apply(lambda x : x.split('/')[0] if '/' in x else x)
问题是如何将相关的_数据帧与原始数据帧结合起来?我的尝试是:

data.loc[data['col_1']==2] = relevant_rows
但这不起作用,我认为,因为这里使用的.loc[]操作符返回的是数据帧的副本,而不是数据帧本身

有没有一个快速的方法来实现我所需要的

我试图编辑的数据帧如下所示:

col_1   col_2
1   100
2   information/string
2   information/string
3   4
1   600
2   information/string
3   7
2   information/string
我的目标是:

col_1   col_2
1   100
2   information
2   information
3   4
1   600
2   information
3   7
2   information


i、 e.第2列中有字符串的所有行都将被编辑。

看起来您可以只执行以下操作:

df['relevant_rows'] = df['col_2'].apply(lambda x : x.split('/')[0] if '/' in x else x)
这对我有用

data.col_2.replace('/.*','', regex=True, inplace=True)
data
   col_1        col_2
0      1          100
1      2  information
2      2  information
3      3            4
4      1          600
5      2  information
6      3            7
7      2  information

“col_2”中的数据类型是混合的,这将不起作用。我已经更新了答案,你的解决方案将不起作用,因为我可以将映射应用到col_2中的每个项目。你可以显示你希望最终得到的数据帧吗?@mikksu我已经更新了问题,以显示我的意思