为什么我会收到以下错误消息?我正在尝试将函数应用于重复列。请不要告诉我解决方案是做类似df["a"] = 2 * df["a"]
的事情;这是一个愚蠢的例子,我现在正在研究更复杂的事情。
>>> df = pd.DataFrame({"a" : [0,1,2], "b" : [1,2,3]})
>>> df[["a", "a"]].apply(lambda x: x[0] + x[1], axis = 1)
Traceback (most recent call last):
File "C:UsersAlexanderAnaconda3libsite-packagespandasindexesbase.py", line 1980, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandasindex.pyx", line 103, in pandas.index.IndexEngine.get_value (pandasindex.c:3332)
File "pandasindex.pyx", line 111, in pandas.index.IndexEngine.get_value (pandasindex.c:3035)
File "pandasindex.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandasindex.c:3955)
File "pandasindex.pyx", line 169, in pandas.index.IndexEngine._get_loc_duplicates (pandasindex.c:4236)
TypeError: unorderable types: str() > int()
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:UsersAlexanderAnaconda3libsite-packagespandascoreframe.py", line 4061, in apply
return self._apply_standard(f, axis, reduce=reduce)
File "C:UsersAlexanderAnaconda3libsite-packagespandascoreframe.py", line 4157, in _apply_standard
results[i] = func(v)
File "<stdin>", line 1, in <lambda>
File "C:UsersAlexanderAnaconda3libsite-packagespandascoreseries.py", line 583, in __getitem__
result = self.index.get_value(self, key)
File "C:UsersAlexanderAnaconda3libsite-packagespandasindexesbase.py", line 2000, in get_value
raise IndexError(key)
IndexError: (0, 'occurred at index 0')
IIUC 您需要将x[0]
和x['1']
更改为x.a
,因为没有列0
和1
:
a = df[["a", "a"]].apply(lambda x: x.a + x.a, axis = 1)
print (a)
a a
0 0 0
1 2 2
2 4 4
但是,如果重复性列具有不同的值,请使用iloc
:
import pandas as pd
df = pd.DataFrame({"a" : [0,1,2], "b" : [1,2,3]})
df.columns = ['a','a']
print (df)
a a
0 0 1
1 1 2
2 2 3
df['sum'] = df.iloc[:,0] + df.iloc[:,1]
print (df)
a a sum
0 0 1 1
1 1 2 3
2 2 3 5
什么相同:
df['sum'] = df.a.apply(lambda x: x.iloc[0] + x.iloc[1], axis = 1)
print (df)
a a sum
0 0 1 1
1 1 2 3
2 2 3 5