我正在尝试逐行替换单个列值(现在使用整体数据帧替换来解决),如果单词列表不同,则替换单词列表。它们具有匹配的长度,因此索引应该起作用。
例如如果在列表一中为“朋友”,请在列表二中替换为“伙伴”。
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
答案 0 :(得分:1)
通常,在使用数据框时,迭代并不是最好的方法。您可以改用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
或用于单列替换(此处仅在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