【发布时间】:2019-03-18 10:18:07
【问题描述】:
假设我有以下数据框:
xx yy tt
0 2.8 1.0 1.0
1 85.0 4.48 6.5
2 2.1 8.0 1.0
3 8.0 1.0 0.0
4 9.0 2.54 1.64
5 5.55 7.25 3.15
6 1.66 0.0 4.0
7 3.0 7.11 1.98
8 1.0 0.0 4.65
9 1.87 2.33 0.0
我想用它来创建一个 for 循环,该循环遍历 df 中的所有点并计算到所有其他点的欧几里得距离。例如:循环将遍历点 a 并获得从点 a 到点 b、c、d...n 的距离。然后它会去点 b,它会得到点 a、c、d...n 的距离,等等。
一旦我得到距离值,我想要一个距离值的value_counts(),但为了节省内存,我不能只是value_counts() 我从这个 foor 循环中得到的所有结果,因为我真正的 df太大了,我最终会用完内存。
所以我的想法是对距离向量执行value_counts() 操作,这将给出一个包含值及其各自计数的 2 列数据框,然后当它遍历点 b 并获得所有距离时,我想将新值与第一个循环中的前一个value_counts() df 进行比较,并检查是否有任何重复值,如果是,那么我想+= 重复值的计数器,如果没有找到重复值,我想append()所有那些距离df没有重复值的行。
这是我目前所得到的:
import pandas as pd
counts = pd.DataFrame()
for index, row in df.iterrows():
dist = pd.Series(np.sqrt((row.xx - df.xx)**2 + (row.yy - df.yy)**2 + (row.tt - df.tt)**2)) # Create a vector containing all the distances from each point to the others
counter = pd.Series(dist.value_counts(sort = True)).reset_index().rename(columns = {'index': 'values', 0:'counts'}) # Get a counter for every value in the distances vector
if index in counter['values']:
counter['counts'][index] += 1 # Check if the new values are in the counter df, if so, add +1 to each repeated value
else:
counts = counts.append((index,row)) # If no repeated values, then append new rows to the counter df
预期的结果是这样的:
# These are the value counts for point a and its distances:
values counts
0 0.000000 644589
1 0.005395 1
2 0.005752 1
3 0.016710 1
4 0.023043 1
5 0.012942 1
6 0.020562 1
现在在 b 点的迭代中:
values counts
0 0.000000 644595 # Value repeated 6 times, so add +6 to the counter
1 0.005395 1
2 0.005752 1
3 0.016710 3 # Value repeated twice, so add +2 to the counter
4 0.023043 1
5 0.012942 1
6 0.020562 1
7 0.025080 1 # New value, so append a new row with value and counter
8 0.022467 1 # New value, so append a new row with value and counter
但是,如果您将print (counts) 添加到循环末尾以检查此循环的执行结果,您将看到一个空数据框。这就是我问这个问题的原因。为什么这段代码给出了一个空的df,我怎样才能让它按照我想要的方式工作?
如果您需要更多额外的解释、不清楚的地方或需要更多信息,请不要犹豫。
提前致谢
【问题讨论】:
-
因为你的循环永远不会进入 else 条件,这就是为什么你的数据框是空的
-
哼什么是组合?它是一个特殊的图书馆吗?
-
不,是df。给我一秒钟,我会编辑问题,这样会更清楚
标签: python python-3.x pandas loops dataframe