2016-03-07 31 views
4

我有一个包含大约90k字符串的列表和一个包含多列的数据框,我有兴趣检查列表中的字符串是否在column_1中,并且它是否分配相同值为第2列。用列表理解修改数据框列

我可以这样做:

for i in range(len(my_list)): 
    item = list[i] 
    for j in range(len(df)): 
     if item == df['column_1'][j]: 
      df['column_2'][j] = item 

但我宁愿避免嵌套循环

我想这

for item in my list: 
    if item in list(df['column _1']): 
      position = df[df['column_1']==item]].index.values[0] 
      df['column_2'][position] = item 

,但我认为,这个解决方案是更慢,更难阅读,这个操作可以通过简单的列表理解来完成吗?

编辑。

第二个解决方案它速度相当快,大约一个数量级。 这是为什么?看来,在这种情况下它必须为马赫两次搜索:

这里:

if item in list(df['column _1']) 

这里:

possition = df[df['column_1]=='tem]].index.values[0] 

尽管如此,我宁愿一个简单的解决方案。

回答

3

您可以通过拆分你进入两个不同的步骤中描述的过滤和分配的行动做到这一点。

熊猫系列对象包含'isin'方法,可以让您识别column_1值位于my_list中的行并将结果保存为布尔值系列。这可以反过来用的.loc索引方法可以使用如果COLUMN_2尚不存在将值从适当的行复制从第1列到第2列

# Identify the matching rows 
matches = df['column_1'].isin(my_list) 
# Set the column_2 entries to column_1 in the matching rows 
df.loc[matches,'column_2'] = df.loc[matches,'column_1'] 

,这种方法创建COLUMN_2并设置non_matching值到NaN。 .loc方法用于避免在执行索引操作时对数据副本进行操作。

+0

我觉得你并不需要第二df.loc [...],所以它会工作也很喜欢这:df.ix [(df ['column_1']。isin(my_list)),'column_2'] = df ['column_1']作为一行 – MaxU

2

比方说,你有一个清单:

l = ['foo', 'bar'] 

和数据帧:

df = pd.DataFrame(['some', 'short', 'string', 'has', 'foo'], columns=['col1']) 

您可以使用df.apply

df['col2'] = df.apply(lambda x: x['col1'] if x['col1'] in l else None, axis=1) 

df 
    col1 col2 
0 some None 
1 short None 
2 string None 
3 has  None 
4 foo  foo 
1

尝试使用下面的衬板:

df.loc[(df['column_1'].isin(my_list)), 'column_2'] = df['column_1'] 

到@ res_edit的解决方案不同的是缺少第二df.loc[]的应该快一点工作...