我得到了这个代码:
df['newCol'] = [x if x in df['subject'] else np.NAN for x in myList]
我收到的错误是:ValueError: Length of values (97508) does not match length of index (100)
我试图实现的是检查myList
(这是str的列表(中的每个项目,如果其中一个或多个项目存在于'subject'
列(这是一个可变长度的字符串列,可能包含也可能不包含myList
中的一个或更多个项目(中,则'newCol'
列将填充myList
中匹配项目的列表;否则,在没有匹配的情况下,Nan或空列表。
ValueError表示,值的长度与索引的长度不同。我能看到的是,100是df的长度,而97508是df的长度。
我做错了什么?感谢
pakpe的答案问题与原始代码中的逻辑相同。你说你想要
"newCol"列填充有匹配项的列表来自myList;否则,在不匹配的情况下,Nan或空列表
你的两次尝试都没有说明这一点。
import pandas as pd
import numpy as np
#initialize with blank list in newCol
testdata = [['Subject Test1 yes', []], ['Subject Test2 yes', []], ['Subject Test3 no', []]]
myList = ['yes', '2', 'random']
#create dataframe
df = pd.DataFrame(testdata, columns=['subject', 'newCol'])
# set column type of newCol as object to ensure it may contain a list of values
df['newCol'] = df['newCol'].astype('object')
for index, row in df.iterrows():
for x in myList:
if x in row['subject']:
df.at[index, 'newCol'].append(x)
print(df)
或者,如果你想用NaN填充,你可以做:
for index, row in df.iterrows():
for x in range(len(myList)):
if myList[x] in row['subject']:
df.at[index, 'newCol'].append(myList[x])
if x == len(myList)-1 and df.at[index, 'newCol'] == []:
df.at[index, 'newCol'] = np.NAN
输出:
myList = ['yes', '2', 'random']
subject newCol
0 Subject Test1 yes [yes]
1 Subject Test2 yes [yes, 2]
2 Subject Test3 no [nan]
以下是如何:
df = pd.DataFrame({'subject':['a','b','c','d','e']})
myList = ['c','e']
df['newCol'] = df[df['subject'].apply(lambda x: x in myList)]
print(df)
#
subject newCol
0 a NaN
1 b NaN
2 c c
3 d NaN
4 e e
我最终得到了这个:
for row in df.itertuples():
for x in myList:
if x in row.subject:
df.iat[row.Index, 3].append(x)
因为CCD_ 8比CCD_。然而,考虑到我的数据帧超过100000行,myList
大约有90000个元素,执行它需要几分钟的时间。我希望我可以利用一些pandas矢量化方法来提高性能,但到目前为止,我还无法找到解决方案。有什么建议吗?