首页 > 解决方案 > 如何用列表中的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

标签: pythonpandasloopsdataframe

解决方案


通常,在使用数据框时,迭代不是最好的方法。您可以改用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

推荐阅读