日安!我在更新csv文件时遇到了一些问题(我正在使用熊猫)。如果row元素与我定义的数组相同,我希望代码删除csv文件中的一行。
例如,如果csv文件中有以下行:
and 2
hi 3
or 4
is 5
hello 6
而定义的数组a由以下方法提供:
a = ['and', 'or', 'is']
d = {}
for k, v in reader.values:
if a == k:
break
else:
d[k] = int(v)
读取器是我用来使用熊猫打开csv文件的变量的名称。
我期待一个字典,其中列在数组中的单词不会存储在d中。我期望这样的输出:
{'hi':3, 'hello': 6}
当我检查输出时,数组a中列出的单词仍然包含在字典中。我希望你能帮我,谢谢!
发布于 2019-06-24 07:58:59
使用df.replace()
将列表a
替换为nan
,然后使用dropna()
获取dict()
#replace 0 with first col name
d=dict(df.replace(a,np.nan).dropna(subset=[0]).values)
{'hi': 3, 'hello': 6}
发布于 2019-06-24 07:30:50
使用熊猫isin()
假设您的数据文件如下所示,我将其命名为df
,列为"word“和"number”。
word number
0 and 2
1 hi 3
2 or 4
3 is 5
4 hello 6
我会使用熊猫的isin函数。
In [1]: a = ['and', 'or', 'is']
df[~df['word'].isin(a)]
Out[1]: word number
1 hi 3
4 hello 6
然后,如果你想要一本字典,你可以直接压缩你需要的列。
In [2]: a = ['and', 'or', 'is']
df2 = df[~df['word'].isin(a)]
dict(zip(df2['word'], df2['number']))
Out[2]: {'hello': 6, 'hi': 3}
使用原始代码
如果希望原始代码正常工作,只需替换if
和break
语句即可。
d = {}
for k, v in df.values:
print(k)
if k in a:
continue
else:
d[k] = int(v)
注意,a
是一个列表,k
是一个字符串。因此,a==k
将始终计算为false,并且您永远不会跳过值。相反,您需要检查是否是k in a
。而且,break
并不是您真正想要的,因为当您在a
中遇到一个值时,它会立即停止for循环。您需要的是continue
,这样您就可以转到数据帧中的下一个值了。
https://stackoverflow.com/questions/56738718
复制