![](/img/trans.png)
[英]Pandas dataframe: Creating a new column based on data from other columns
[英]Error when creating a new column in a Pandas dataframe from two other columns
我有以下(玩具)数据集:
import pandas as pd
import numpy as np
df = pd.DataFrame({'Manufacturer':['Allen Edmonds', 'Louis Vuitton 23', 'Louis Vuitton 8', 'Gulfstream', 'Bombardier', '23 - Louis Vuitton', 'Louis Vuitton 20'],
'System':['None', 'None', '14 Platinum', 'Gold', 'None', 'Platinum 905', 'None']
})
接下来,我基于现有的两个列创建一个名为Manufacturer
的列:
df.loc[(df['Manufacturer'].str.contains('Louis')) &
(df['System'].str.contains('Platinum')),
'Pricing'] = 'East Coast'
在玩具数据集上,这种方法按预期工作。 但是,在生产数据(不幸的是,我无法共享)上,我看到以下错误消息:
KeyError: "None of [Float64Index([nan, nan, nan, nan, nan, nan...], \n dtype='float64', length=583)] are in the [index]"
起初,我认为错误可能是由列标题中的空格引起的。 但是,看起来情况并非如此。
列标题分配如下:
for elem in elements:
d = {
'Manufacturer' : issue.fields.manufacturer,
'System' : issue.fields.system
}
(数据来自数据库)
知道是什么导致了这个关键错误吗?
也许我需要使用以下改编版:
df['Pricing'] = np.where(df['Manufacturer'].str.contains('Louis'), 'East Coast', 'None')
但是,我不确定如何在两个条件下使用np.where
......(请参阅如何根据我的原始问题对一个或多个其他列的条件子字符串搜索在 Pandas 数据np.where
创建列)。
提前致谢!
没有数据就很难理解错误。
您可以通过这种方式在 2 个条件下尝试 np.where:
df['Pricing']=np.where((df['Manufacturer'].str.contains('Louis') & df['System'].str.contains('Platinum')), 'East Coast', None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.