我知道這是一個超級基本的問題,但我被卡住了。
我正在嘗試創建一個資料框。我想創建一個包含 for 回圈結果的資料框。
def nearest_neighbors(coordinates, wafer_map):
for row in coordinates:
map_tree = spatial.cKDTree(wafer_map)
distance, index = map_tree.query(row)
cols = ["Coordinates", "Distance to nearest coordinates", "Nearest coordinates"]
num_list = [row, distance, wafer_map[index]]
lst = []
for a in range(len(coordinates)):
lst.append(num_list)
df1 = pd.DataFrame(lst, columns=cols)
print(df1)
test = nearest_neighbors(coordinates, wafer_map)
print(test)
這將生成具有正確行數的資料框,但每行包含相同的資料。
示例num_list:[array([ 45.96194078, -53.03300859]), 0.11039021695784783, array([ 45.96618342, -53.14331725])]
編輯:
現在它為每一行生成一個單獨的資料框......并且資料是正確的。如何將所有這些單獨的資料幀連接成一個資料幀?
def nearest_neighbors2(coordinates, wafer_map):
for row in coordinates:
# construct a kd-tree
map_tree = spatial.cKDTree(wafer_map)
# find k nearest neighbors for each (x,y) coordinate
distance, index = map_tree.query(row)
cols = ["Coordinates", "Distance to nearest coordinates", "Nearest coordinates"]
num_list = [row, distance, wafer_map[index]]
d = defaultdict(list)
df2 = pd.DataFrame([])
for a, b in zip(cols, num_list):
d[a].append(b)
df2 = df2.append(d, ignore_index=True)
print(df2)
uj5u.com熱心網友回復:
在內部 for 回圈中,您num_list為整個 for 回圈長度附加相同的內容。我認為改變那部分應該做到這一點。而對于pd.DataFrame,資料不應該是一個串列,它應該是字典格式。
uj5u.com熱心網友回復:
每行將包含相同的資料,因為您在內部 for 回圈num_list中lst每次都附加相同的資料。此外,由于您df1在外部 for 回圈內,您將只能將上次迭代結果存盤在df1.
uj5u.com熱心網友回復:
弄清楚了。
def nearest_neighbors3(coordinates, wafer_map):
list_of_dicts = []
for row in coordinates:
# construct a kd-tree
map_tree = spatial.cKDTree(wafer_map)
# find k nearest neighbors for each (x,y) coordinate
distance, index = map_tree.query(row)
cols = ["Coordinates", "Distance to nearest coordinates", "Nearest coordinates"]
results = [row, distance, wafer_map[index]]
results_dict = dict(zip(cols, results))
list_of_dicts.append(results_dict)
df = pd.DataFrame(list_of_dicts)
return df
calculate_pt = nearest_neighbors(coordinates, wafer_map)
print(calculate_pt)
感謝大家的幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/346102.html
標籤:Python
上一篇:如何在串列中使用字串格式?
