将具有相同行号的两个DF连接起来将创建一个具有不同行号的新DF

问题描述 投票:0回答:1

例如:An example for what I'm expecting to get

在我的真实数据中,尽管我连接了两个具有相同行号的DF,但是新DF的行比我要连接的两个DF多。

df_numeric = df.iloc[:,0:10]
numeric_cols = df_numeric.columns.tolist()
df_categorial = df.iloc[:,10:]
from sklearn.preprocessing import Normalizer
transformer = Normalizer().fit(df_numeric)  # fit does nothing.
df_numeric = transformer.transform(df_numeric)
df_numeric = pd.DataFrame(df_numeric)
df_numeric.columns = numeric_cols 
df= pd.concat([df_numeric , df_categorial] , axis = 1  )

我得到:my real DF after the concat

我尝试了文森特说的话:

df_numeric.reset_index(inplace=True, drop=True) 
df_categorial.reset_index(inplace=True, drop=True) 
df = pd.concat([df_numeric , df_categorial] , axis = 1  )

我认为现在可以正常工作。我不明白为什么在统计上会出现问题-在我休息索引之前,它们在两个DF中都是相同的

python pandas concat
1个回答
0
投票

您可以使用合并执行此操作。这是一个示例:

将熊猫作为pd导入

df_numeric = pd.DataFrame(
    {
        'index' : [1,2,3],
        'age': [13,60,30],
        'weight': [50, 80, 70]
    }
)

df_categorical = pd.DataFrame(
    {
        'index' : [1,2,3],
        'has_car': [1,1,1],
        'has_pet': [1, 0, 0],
        'has_brother': [1, 1, 0]
    }
)

df = df_numeric.merge(df_categorical, on='index')
print(df)
© www.soinside.com 2019 - 2024. All rights reserved.