Python 将两个具有相同行数的DFs连接起来将创建一个具有不同行数的新DFs
例如: 在我的实际数据中,尽管我用相同的行号连接了两个DFs,但新DF的行数比我连接的两个多Python 将两个具有相同行数的DFs连接起来将创建一个具有不同行数的新DFs,python,pandas,concat,Python,Pandas,Concat,例如: 在我的实际数据中,尽管我用相同的行号连接了两个DFs,但新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
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 )
我得到:
我试过文森特说的话:
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中都是相同的您可以使用merge来实现这一点。以下是一个例子: 作为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)
轴为1的pd.concat将在同一索引上连接。如果您的行按您想要的方式排序,那么在concatreset_index之前重置_index-在括号中写什么?什么都没有。重置索引只会重置索引。有关详细信息,请参见发布df和df_分类的样本数据。