【问题标题】:Iterating over pandas dataframe with several conditions在多个条件下迭代 pandas 数据框
【发布时间】:2020-05-02 20:35:11
【问题描述】:

所以我有这个数据框,其中包含不同点的位置、X、Y、Z 和其他几个属性。然后,我有另一个名为 path() 的字典,其中包含形成轨迹的不同点。这些点包含在数据框中。

出于绘图的原因,我只想将路径()中的点设置为“路径”列等于 2。如何识别数据框的哪些点在此路径中并更改它们的“路径”属性?

澄清:

路径是这样的:

path = {12, 34, 14}

和 pos{} 为路径的每个节点提供 [x,y,z]

pos = {12: [3, 4, 2], 34: [1, 3, 4], 14: [5, 4, 5]}

其中 [3, 4, 2] = [x, y, z] 就像数据框中的那些。所以我想要做的是将数据框中的“路径”列从 1 更改为 2,以获取与此匹配的数据框中的位置。因此,例如,如果对于 14: [5, 4, 55],数据框中有一行 X = 5、Y = 4 和 Z = 55,我希望这一行的路径 = 2。

这是我尝试过的,我认为它应该有效,但它没有。 Basicallt 我尝试过滤位置,然后相应地修改数据框。

(这里我尝试从 0 更改为 1 而不是 1 更改为 2,因为我给您的 df 的图像是我在尝试此操作时修改但忽略它的图像)

df['path'] = np.zeros(len(df.index))

filt1 = (df['eventID'] == 98)
df_path = df[filt1]

for node in path:

     A, B, C = pos[node]
     filt2 = (df['X'] == A) & (df['Y'] == B) & (df['Z'] == C)

     df_path[filt2]['path'].replace({0:1})

另外,我收到以下警告:

UserWarning:

Boolean Series key will be reindexed to match DataFrame index.

对不起,如果我“违反”了一些不受欢迎的规则,我是新来的。 非常感谢

阿莱克斯

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

解决了!

df['path'] = np.zeros(len(df.index))

filt1 = (df['eventID'] == 98)
df_path = df[filt1]

for node in path:

   A, B, C = pos[node]
   filt2 = (df['X'] == A) & (df['Y'] == B) & (df['Z'] == C)

   df_path['path'].loc[filt2] = 1

【讨论】:

    【解决方案2】:

    1.从字典中找到你想要的键using this

    >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
    >>> keys = dishes.keys()
    >>> # keys and values are iterated over in the same order (insertion order)
    >>> list(keys)
    ['eggs', 'sausage', 'bacon', 'spam']
    

    2。现在更改替换路径属性 using this

    df = pd.DataFrame({"column1": ["a", "b", "a"]})
    print(df)
    OUTPUT
      column1
    0       a
    1       b
    2       a
    
    df["column1"].replace({"a": "x", "b": "y"}, inplace=True)
    print(df)
    OUTPUT
      column1
    0       x
    1       y
    2       x
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-12
      • 2021-09-26
      • 2016-01-19
      • 2020-08-29
      • 2022-01-02
      • 2017-01-04
      • 2019-01-14
      • 1970-01-01
      相关资源
      最近更新 更多