我擁有的是一個基本資料框,我想根據索引位置從中提取兩個值。所以為此:
| 第一列 | 第二列 |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
我想從 first_column 中提取第 1 行和第 2 行 (1 2) 中的值,然后從 first_column 中提取第 2 行和第 3 行 (2 3) 中的值,依此類推,直到我遍歷了整列。我遇到了四回圈的問題,并堅持獲取下一個索引值。
我有如下代碼:
import pandas as pd
data = {'first_column': [1, 2, 3, 4, 5],
'second_column': [1, 2, 3, 4, 5],
}
df = pd.DataFrame(data)
for index, row in df.iterrows():
print(index, row['first_column']) # value1
print(index 1, row['first_column'].values(index 1)) # value2 <-- error in logic here
忽略列印??,最終將成為回傳的變數,我如何改進它以回傳(1 2)、(2 3)、(3 4)、(4 5)等?
另外,使用 iteritems() 方法而不是 iterrows 是否更容易完成?
uj5u.com熱心網友回復:
不確定這是否是您想要實作的目標:
(temp= df.assign(second_column = df.second_column.shift(-1))
.dropna()
.assign(second_column = lambda df: df.second_column.astype(int))
)
[*zip(temp.first_column.array, temp.second_column.array)]
[(1, 2), (2, 3), (3, 4), (4, 5)]
來自@HenryEcker 的一個更簡單的解決方案:
list(zip(df['first_column'], df['first_column'].iloc[1:]))
uj5u.com熱心網友回復:
我不知道這是否能回答你的問題,但也許你可以試試這個:
for i, val in enumerate(df['first_column']):
if val 1>5:
break
else:
print(val,", ",val 1)
uj5u.com熱心網友回復:
如果您想以同樣的方式使用這些專案,您應該考慮使用iloc而不是使用iterrow.
out = []
for i in range(len(df)-1):
print(i, df.iloc[i]["first_column"])
print(i 1, df.iloc[i 1]["first_column"])
out.append((df.iloc[i]["first_column"],
df.iloc[i 1]["first_column"]))
print(out)
[(1, 2), (2, 3), (3, 4), (4, 5)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/315511.html
