Zac*_*ris 14 python warnings pandas
我遇到了 Pandas v2.1.0+ 的问题,我无法弄清楚。
我的 pandas 数据框中有一个列列表,需要使用自定义函数进行转换。新值取决于数据中的多个列,因此我使用 apply 就地转换列:
my_columns_to_convert = ['col1','col2','col3']
for k in my_columns_to_convert:
df[k] = df[[k,colx]].apply(lambda x: convert_my_data(value_1_in=x[0],value_2_in=x[1]),axis=1)
Run Code Online (Sandbox Code Playgroud)
这在以前版本的 pandas 中运行得很好。但现在我得到:
FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
Run Code Online (Sandbox Code Playgroud)
但我没有使用 loc 或 iloc,到目前为止我所审查的所有内容似乎都表明这是问题所在。我该如何编写这段代码,以便将来以“正确”的方式进行操作?
在 Pandas 中使用以前的方法确实有效。
这可以通过这个简单的例子FutureWarning来触发:2.1.0
ser = pd.Series({"A": "a", "B": "b", "C": "c"})
# A a
# B b
# C c
# dtype: object
print(ser[1]) # gives 'b' but with a FutureWarning: Series.__getitem__ treating keys..
Run Code Online (Sandbox Code Playgroud)
目标是在对DataFrame 和 Series进行 [ ] 索引时具有一致的行为。请记住,df[1]不会返回位于该 DataFrame 的第二个位置的列,并且会触发 a KeyError(除非文字 0 是实际列,在这种情况下,0将返回该列)。
因此,根据您的代码,您的df(请参阅下面我的想象)很可能没有默认索引(即整数范围或至少整数列表)。因此,当在这里对每个系列进行切片时x[0],x[1]虽然索引是字符串["A", "B", "C"],但 pandas 会警告您使用x.iloc[0]andx.iloc[1]代替。
my_columns_to_convert = ['col1', 'col2', 'col3']
df = pd.DataFrame(
np.arange(12).reshape(-1, 4),
index=list("ABC"), columns= my_columns_to_convert + ["colx"]
)
# col1 col2 col3 colx
# A 0 3 6 3
# B 28 35 42 7
# C 88 99 110 11
def convert_my_data(value_1_in, value_2_in):
return value_1_in * value_2_in # a simple calculation
for k in my_columns_to_convert:
df[k] = (
df[[k, "colx"]].apply(
lambda x: convert_my_data(value_1_in=x[0], value_2_in=x[1]), axis=1)
)
# the FutureWarning is displayed three times (= the length of the Series) :
Run Code Online (Sandbox Code Playgroud)
FutureWarning:
Series.__getitem__不推荐将键视为位置。在未来的版本中,整数键将始终被视为标签(与 DataFrame 行为一致)。要按位置访问值,请使用ser.iloc[pos]:lambda x: convert_my_data(value_1_in=x[0], value_2_in=x[1]), axis=1)
顺便说一句,您的代码似乎效率不高,并且可能很容易矢量化。
| 归档时间: |
|
| 查看次数: |
14404 次 |
| 最近记录: |