python - 如何用列表中的for循环替换熊猫数据框?
问题描述
如果在不同的列表中找到单词,我正在尝试根据要替换的单词列表逐行替换单个列值(现在解决整个数据框替换)。它们具有匹配的长度,因此索引应该可以工作。
前任。如果列表一中的“朋友”,则替换为列表二中的“好友”。
data = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']}
pd.DataFrame.from_dict(data)
numlist = [1,2,3]
abclist = ["z","x","y"]
for n in numlist:
pd.DataFrame.replace(n, abclist[numlist.index(n)])
出现错误:请帮助
TypeError Traceback (most recent call
last)
<ipython-input-12-4e44f23fd530> in <module>()
6
7 for n in numlist:
----> 8 pd.DataFrame.replace(n,abclist[numlist.index(n)])
9 DataFrame
/anaconda3/lib/python3.6/site-packages/pandas/core/frame.py in
replace(self, to_replace, value, inplace, limit, regex, method)
3790 def replace(self, to_replace=None, value=None, inplace=False,
limit=None,
3791 regex=False, method='pad'):
-> 3792 return super(DataFrame,
self).replace(to_replace=to_replace,
3793 value=value,
inplace=inplace,
3794 limit=limit,
regex=regex,
TypeError: super(type, obj): obj must be an instance or subtype of type
解决方案
通常,在使用数据框时,迭代不是最好的方法。您可以改用pandas
方法:
在您的情况下,您可以使用 为您的替换创建字典zip
,然后使用replace
.
起始数据框:
>>> df
col_1 col_2
0 3 a
1 2 b
2 1 c
3 0 d
对于整个数据框替换:
my_dict = dict(zip(numlist, abclist))
df.replace(my_dict, inplace=True)
>>> df
col_1 col_2
0 y a
1 x b
2 z c
3 0 d
或者对于单列替换(这里,仅替换 in col_1
):
my_dict = dict(zip(numlist, abclist))
df['col_1'].replace(my_dict, inplace=True)
>>> df
col_1 col_2
0 y a
1 x b
2 z c
3 0 d
推荐阅读
- http-status-code-404 - Cognos Analytics Rest Api/Api-docs 404 not found 问题
- r - 使用具有多个时间测量的变量进行迭代:purrr 和 map() 函数
- typescript - 使用 typescript 时如何让 esbuild 包含内部依赖项
- python - 使用列表中的掩码值掩码 python 列表/数组 - 使用 if/else
- python - 使用大型 numpy 数组将 dict 写入 CSV
- angular - SOAP 调用在 JavaScript 中返回 HTML,但返回带有 SOAP UI 的 XML
- xml - 阻止具有单个子节点且 NodeType = element 的 XML 子节点的自动展开
- c# - 为什么带有异常的异步任务会成功完成?
- keras - 多个图像作为 Keras CNN 中的一个输入
- flutter - 如何让我在 Flutter 中退出