python - 如果满足文本长度条件,熊猫将列的值设置为其他列的值
问题描述
数据如下所示:
df
idx column1 column2
0 text(100 words) text
1 text(20 words) text
2 text(30 words) text
3. text(500 ords) text
我需要这样的东西:
df
idx column1 column2
0 text(100 words) text
1 text(20 words) text(20 words)
2 text(30 words) text(30 words)
3. text(500 words) text
每当 column1 的文本长度值低于 50 个字时,我需要替换 column2 的值。
我想做的事情的想法是where (len(df.column1.str.split()) <= 50) set value of column2 to the value of column1
。
到目前为止我所做的是:
df.loc[len(df.column1.str.split()) <= 50, 'column2'] = df['column1']
和
mask = (len(df['column1'].str.split()) <= 50)
df['column2'][mask] = df['column1']
但它不能正常工作。在这两种情况下,它都会引发以下错误:“不能使用单个布尔值来索引 setitem”。有什么建议么?
解决方案
你可以这样做:
df.loc[df.column1.str.len() < 50, 'column2'] = df.column1
OP评论后的数据示例:
In [624]: df
Out[624]:
column1 column2
0 text(100 words) text
1 text(200 words) t
2 text(10 words) r
3 text(40 words) q
为简单起见,假设长度小于 15
In [637]: df.loc[df.column1.str.len() < 15, 'column2'] = df.column1
In [638]: df
Out[638]:
column1 column2
0 text(100 words) text
1 text(200 words) t
2 text(10 words) text(10 words)
3 text(40 words) text(40 words)
因此,您可以看到 column2 中的最后 2 行已被 column1 的值替换,因为它们的长度小于 15。