有没有办法在for循环中更改DataFrame?例如,而不是:
df_train[df_train > 1] = 1
df_test[df_test > 1] = 1
类似的东西:
for frame in [df_train, df_test]:
frame = frame[frame > 1] = 1
在此版本中,原始DataFrame不会更改。如何通过for循环实现这一目标?
答案 0 :(得分:3)
在以下行中,移除frame =
:
frame = frame[frame > 1] = 1
#^^^^^^^
>>> import pandas as pd
>>>
>>> df_train = pd.DataFrame([0.1, 0.2, 3], columns=['a'])
>>> df_test = pd.DataFrame([0.1, 5, 0.3], columns=['a'])
>>> df_train[df_train > 1] = 1
>>> df_test[df_test > 1] = 1
>>> for frame in [df_train, df_test]:
... frame[frame > 1] = 1
...
>>> df_train
a
0 0.1
1 0.2
2 1.0
>>> df_test
a
0 0.1
1 1.0
2 0.3