【发布时间】:2020-11-28 14:44:40
【问题描述】:
我有以下数据框:
cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','No Brand'],
'Country': ['Japan','No Country','United States','Germany']
}
df = pd.DataFrame(cars, columns = ['Brand', 'Country'])
df.head(4)
Brand Country
0 Honda Civic Japan
1 Toyota Corolla No Country
2 Ford Focus United States
3 No Brand Germany
希望在数据框中创建一个新列,该列将根据“品牌”和“国家”列的值进行组合。如果 Brand 列中有“No Brand”值,则 Desc 列仅采用 Country 列中的值。如果 Country 列中有“No Country”值,则 Desc 列仅采用 Brand 列中的值。期望的输出:
Brand Country Desc
0 Honda Civic Japan Honda Civic Japan
1 Toyota Corolla No Country Toyota Corolla
2 Ford Focus United States Ford Focus United States
3 No Brand Germany Germany
如果它检查一列中的字符串,我可以这样做,但不确定如何处理两列。现在我只能在我想要的条件下检查布尔值。
df['Desc'] = df['Brand'].str.contains("No Brand") | df['Country'].str.contains("No Country")
Brand Country Desc
0 Honda Civic Japan False
1 Toyota Corolla No Country True
2 Ford Focus United States False
3 No Brand Germany True
我读到不建议迭代数据帧并避免这样做。
【问题讨论】:
标签: python pandas numpy dataframe