【发布时间】:2017-09-15 00:20:22
【问题描述】:
我正在将 Excel 电子表格转换为 Python,以便自动化和加快多项任务。我需要向 DataFrame 添加几列,并根据前一列中的值向它们添加数据。我使用两个嵌套的 for 循环让它工作,但它真的很慢,而且我知道 Pandas 不是为逐个单元工作而设计的。这是我的问题的一个示例:
import pandas as pd
results = pd.DataFrame({'scores':[78.5, 91.0, 103.5], 'outcomes':[1,0,1]})
thresholds = [103.5, 98.5, 93.5, 88.5, 83.5, 78.5]
for threshold in thresholds:
results[str(threshold)] = 0
for index, row in results.iterrows():
if row['scores'] > threshold:
results.set_value(index, str(threshold), row['outcomes'])
print (results)
以及正确的输出:
outcomes scores 103.5 98.5 93.5 88.5 83.5 78.5
0 1 78.5 0 0 0 0 0 0
1 0 91.0 0 0 0 0 0 0
2 1 103.5 0 1 1 1 1 1
有什么更有效的方法来做到这一点?我一直在玩弄将 DataFrame 转置为按列而不是按行工作的想法,但我什么也做不了。 感谢您的帮助!
【问题讨论】: