【问题标题】:New Pandas DF with index from one DF and columns from another新的 Pandas DF,索引来自一个 DF,列来自另一个
【发布时间】:2018-04-04 16:52:48
【问题描述】:

我有两个数据框。 DF1 和 DF2。我正在比较两者的坐标对之间的绝对距离。我想填充一个新的数据框,其中包含每个 df1 坐标对的行和每个 df2 坐标对的列。

这将导致每个 df1 对和每个 df2 对之间的绝对距离。到目前为止,这是我的代码,我正在努力弄清楚如何在每次迭代中填充新的数据框。

`df_new = pd.DataFrame(index=df1.index.copy())

for idx_crime, x_crime in enumerate(df2['X_COORD']):
    y_crime = df2['Y_COORD'].iloc[idx_crime]
    for idx_subway, x_subway in enumerate(df1['X_COORD']):
        y_subway = df1['Y_COORD'].iloc[idx_subway]
        dist = np.sqrt((x_crime - x_subway)**2 + (y_crime - y_subway)**2)
        append.df_new
return df_new`

它没有运行。关于如何填写这个新数据框的任何想法?

编辑 样本数据

DF2 Coordinates:

    X_COORD      Y_COORD 
0   1007314.0    241257.0
1   1043991.0    193406.0
2    999463.0    231690.0
3   1060183.0    177862.0
4    987606.0    208148.0

DF1 Coordinates:

    X_COORD      Y_COORD
0   1020671.0    248680.0
1   1019420.0    245867.0
2   1017558.0    245632.0

所以 df_new 看起来像这样。只有索引号适用于列标题。我只是想向您展示数据的外观:

                 df2_coord0        df2_coord1        df2_coord2
    df1_coord0   13356.72213       23318.81485       21207.59944
    df1_coord1   12105.8096        24569.93244       19956.64481

【问题讨论】:

  • 当你说它“没有运行”时,你的意思是它抛出了一个错误吗?
  • 什么是append?
  • 我会说您需要 pd.crosstab 和自定义 aggfunc,但如果没有一些示例数据就无从谈起了。
  • @snapcrack 它会抛出一个错误但只是停止

标签: python pandas


【解决方案1】:

我不得不将 df2 分解成更小的 dfs,以免引发内存错误。我将 for 循环更改为这个,它可以工作......只是花了一段时间才到达那里:

df_new = pd.DataFrame(index = df1.index.copy(),columns = df2.index.copy())

for idx_crime, x_crime in enumerate(df2['X_COORD']):
    y_crime = df2['Y_COORD'].iloc[idx_crime]
    for idx_subway, x_subway in enumerate(df1['X_COORD']):
        y_subway = df1['Y_COORD'].iloc[idx_subway]
        dist = np.sqrt((x_crime - x_subway)**2 + (y_crime - y_subway)**2)
        df_new.iloc[idx_subway, idx_crime] = dist
return df_new

【讨论】:

    【解决方案2】:

    显然,append.df_new 是错误的。如果这是您的伪代码,那么您需要将单元格插入数据帧。这里有两种方法: using position indexing 或 using conditional indexing。

    示例代码:

    import pandas as pd
    
    lst = [
        {"a":1,"b":1},
        {"a":2,"b":2}
    ]
    
    df = pd.DataFrame(lst)
    
    df.loc[2] = [3, 3]    #2 here should be your desire index
    df.loc[3] = {"a":4,"b":4} #3 here should be your desire index
    
    print df
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2014-11-30
      • 1970-01-01
      • 2022-08-14
      • 2020-12-13
      相关资源
      最近更新 更多