【问题标题】:Concatenating pandas dataframe on basis of increasing index number and retaining their positon on basis of it在增加索引号的基础上连接熊猫数据框并在此基础上保留它们的位置
【发布时间】:2021-11-22 23:01:50
【问题描述】:

已编辑:

我有一个熊猫数据框如下:

  Class  Sex  SibSp Fare
0  0      0     0     0
2  2      2     2     2
3  3      3     3     3
5  5      5     5     5

我有另一个熊猫数据框如下:

  Class  Sex  SibSp Fare
1  1      1     1     1
4  4      4     4     4

如果我使用连接这两个数据框

pd.concat([traindf,testdf])

我得到以下结果:

  Class  Sex  SibSp Fare
0  0      0     0     0
2  2      2     2     2
3  3      3     3     3
5  5      5     5     5
1  1      1     1     1
4  4      4     4     4 

但是,我想得到如下结果:

   Class  Sex  SibSp Fare
0  0      0     0     0
1  1      1     1     1
2  2      2     2     2
3  3      3     3     3
4  4      4     4     4
5  5      5     5     5

我使用过pd.concat([traindf,testdf]).sort_values(),但这不起作用。关于如何实现这一点的任何想法,以便数据帧根据它们的索引号连接起来。谢谢

【问题讨论】:

  • 你能从样本数据中添加预期的输出吗?是否可以在示例数据中添加 Age 列? Please don't post images of code/data (or links to them)
  • 不,我无法将 Age 列添加到样本数据,因为我使用基于数据框中其他可用特征的线性回归填充年龄值
  • 您也不能通过直接处理 df[df['Age'].isnull()] 来将 df 切入 2。
  • 我不得不将 df 分割成 2,因为我在 Age 值不为 null 的行上训练线性回归,然后尝试预测 Age 值为 null 的第二个 df 上的 Age 值。如果我没有将 df 切片为 2,我将无法训练线性回归模型,因为 NULL 值

标签: python python-3.x pandas dataframe concatenation


【解决方案1】:

您可以在不拆分数据框的情况下填写年龄。但如果你必须拆分它们,那么你可以使用以下内容:

pd.concat([traindf, testdf], sort=False).sort_index()

【讨论】:

  • 然后输出与原始DataFrame相同,如果代码正确,则会引发错误;)
【解决方案2】:

如果要复制所有列,则可以使用 loc 获取切片并覆盖它。

# Create some dummy dataframes
df1 = pd.DataFrame(
    {
        'Pclass': np.random.randint(0,10,10),
        'Fare': np.random.randint(0,10,10),
        'Age': np.random.randint(0,100,10)
    })
df2 = copy.deepcopy(df1[df1['Fare']%2 == 0]*1.5)
print (df1, df2)

# Owerwrite df1 with df2
for i in df2.index:
  if i in df1.index:
    df1.loc[i] = df2.loc[i]

print ("After overwrite")
print (df1)

输出:

   Pclass  Fare  Age
0       7     6   25
1       8     3   34
2       0     4   57
3       9     1   98
4       3     5   58
5       8     0   97
6       9     6   53
7       2     0    1
8       0     5   33
9       2     9   36

   Pclass  Fare    Age
0    10.5   9.0   37.5
2     0.0   6.0   85.5
5    12.0   0.0  145.5
6    13.5   9.0   79.5
7     3.0   0.0    1.5

After overwrite

   Pclass  Fare    Age
0    10.5   9.0   37.5
1     8.0   3.0   34.0
2     0.0   6.0   85.5
3     9.0   1.0   98.0
4     3.0   5.0   58.0
5    12.0   0.0  145.5
6    13.5   9.0   79.5
7     3.0   0.0    1.5
8     0.0   5.0   33.0
9     2.0   9.0   36.0

【讨论】:

  • 我已经编辑了这个问题。请阅读它。这种方法虽然有效,但不适合我,因为我的两个数据框中都没有任何重复的索引值。
【解决方案3】:

如果需要按索引排序使用:

df = pd.concat([traindf,testdf]).sort_index() 

或者如果需要按列排序 Class 使用:

df = pd.concat([traindf,testdf]).sort_values(by=['Class']) 

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 2014-08-29
    • 2011-03-17
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 2011-03-30
    • 2012-05-11
    • 1970-01-01
    相关资源
    最近更新 更多