python - 根据来自另一列的信息用 pandas 填充一个空列
问题描述
我正在尝试根据另一列的信息填充一个空列
我的数据框
A B C
0 F House Are you at home?
1 E House description: to deliver tomorrow
2 F Apt Here is some exemples
3 F House description: a brown table
4 E Apt description: in the bus
5 F House Hello, how are you?
6 E Apt description: keys
所以,我创建了一个 D 列,如果 C 列以“描述”开头,我填写“模糊”,如果不是“嗡嗡”。
new_column['D'] = ''
我试着填满它们
def fill_column(delete_column):
if new_column['D'].loc[new_column['D'].str.startswith('description:'):
new_column['D'] == 'fuzzy'
else:
new_column['D'] == 'buzzy'
return new_column
我的输出:
File "<ipython-input-41-ec3c1407168c>", line 6
else:
^
SyntaxError: invalid syntax
良好的输出:
A B C D
0 F House Are you at home? buzzy
1 E House description: to deliver tomorrow fuzzy
2 F Apt Here is some exemples buzzy
3 F House description: a brown table fuzzy
4 E Apt description: in the bus fuzzy
5 F House Hello, how are you? buzzy
6 E Apt description: keys fuzzy
解决方案
您在这里不需要if-else
语句,您可以使用以下命令在一行中干净地完成此操作np.where
:
df['D'] = np.where(
df['C'].str.startswith('description:'), 'fuzzy', 'buzzy')
您可以通过一次loc
调用来完成此操作,因为您只分配了两个值。
df['D'] = 'buzzy'
df.loc[df['C'].str.startswith('description:'), 'D'] = 'fuzzy'
或者使用df.mask
/df.where
喜欢评论中建议的@jpp:
df['D'] = 'buzzy'
df['D'] = df['D'].mask(df['C'].str.startswith('description:'), 'fuzzy')
最后,使用map
:
m = {True: 'fuzzy', False: 'buzzy'}
df['D'] = df['C'].str.startswith('description:').map(m)
print(df)
A B C D
0 F House Are you at home? buzzy
1 E House description: to deliver tomorrow fuzzy
2 F Apt Here is some exemples buzzy
3 F House description: a brown table fuzzy
4 E Apt description: in the bus fuzzy
5 F House Hello, how are you? buzzy
6 E Apt description: keys fuzzy
推荐阅读
- javascript - 正则表达式字符串组不同的状态
- yaml - 用 Yaml2 中的值替换标记 Yaml1
- jquery - 如何在 .NET 5 中使用 Jquery Ajax Post 发送大型 json 数据
- javascript - 在过滤器函数中使用变量作为键名
- javascript - Mongoose:如何根据另一个字段设置字段的值?
- cmake - CMake 是否支持原始字符串?
- php - PHP 和 SQL 中的输出错误未检测到文件
- amazon-web-services - 跟踪 AWS SES 事件指标
- python - 如何使用 Python 将两个动画制作成两个不同的子图?
- azure-devops - 如何更新我的 Azure DevOps 本地管道任务以包含 MSBuild v17 和 Visual Studio 2022?