【问题标题】:Appending rows to dataframe using an .iterrows() for loop使用 .iterrows() for 循环将行附加到数据帧
【发布时间】: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


【解决方案1】:

如果理解你,你想要每个距离值的出现:

所以我建议你创建一个字典:键是值,键的值是计数:

data = """
   xx      yy      tt
2.8     1.0     1.0
85.0    4.48    6.5
2.1     8.0     1.0
8.0     1.0     0.0
9.0     2.54    1.64
5.55    7.25    3.15
1.66    0.0     4.0
3.0     7.11    1.98
1.0     0.0     4.65
1.87    2.33    0.0
"""

import pandas as pd
df = pd.read_csv(pd.compat.StringIO(data), sep='\s+')

dico ={}                            #i initialize the dict dico
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

    for f in dist:                  #i iterate through dist
        if f in dico:               #the key already exists in dict?
            dico[f] +=dico[f]       #yes i increment the value
        else:
            dico[f]=1               #no i create the key with the new distance and set to 1

print(dico)

输出:

{0.0: 512, 
82.45726408267497: 2, 
7.034912934784623: 2, 
5.295280917949491: 2, 
6.4203738208923635: 2, 
7.158735921934822: 2, 
3.361487765856065: 2, 
6.191324575565393: 2, 
4.190763653560053: 2, 
1.9062528688503002: 2, 
83.15678204452118: 2, 
77.35218419669867: 2, 
76.17993961667337: 2, 
79.56882492534372: 2, 
    :
    :
7.511863949779708: 2,
0.9263368717696604: 2, 
4.633896848226123: 2, 
7.853725230742415: 2, 
5.295819105671946: 2, 
5.273357564208974: 2}

每个值至少有 2 个计数,因为它是一个交叉表和距离(point0 到 point1)相等的距离(point1 到 point0)......

【讨论】:

  • 你好,法国人。这有点接近我想要的,但这是否会将新的计数值与以前的计数值进行比较,如果它们还没有在字典中,则将它们添加到字典中?另外,请记住,如果字典中已经有一些新值,您只需将 +1 添加到该值的计数器。这2个条件满足了吗?非常感谢
  • 我在 prog 中添加了 cmets 可以吗?我已经按照我的理解做了(对不起我的英语)。 600000 行的执行时间会很长...
  • 好的,太好了。我现在明白了一切。非常感谢您的回答。帮了大忙!!不用担心英语:)
  • 乐于助人!!
猜你喜欢
  • 2017-09-29
  • 2017-10-21
  • 2016-01-31
  • 2019-02-22
  • 2017-05-19
  • 2016-10-13
  • 2015-04-05
  • 2016-12-19
  • 1970-01-01
相关资源
最近更新 更多