python - Pandas:concat 函数删除了数据帧的先前排序

标签 python pandas

考虑两个名为“socio_demo”([198 行 x 15 列])和 UPDRS_sorted([198 行 x 70 列])的数据帧。 让我们来做:

socio_demo_sorted = socio_demo.sort_values(['NUMERO_CENTRE_1','NUMERO_INCLUSION_1'])
UPDRS_sorted = UPDRS.sort_values(['NUMERO_CENTRE_2','NUMERO_INCLUSION_2'])

UPDRS_sorted['NUMERO_CENTRE_2'] 给出

Out[22]: 
3     1
9     1
13    1
18    1
24    1
     ..
6     6
16    6
20    6
25    6
34    6
Name: NUMERO_CENTRE_2, Length: 198, dtype: int64

现在让我们连接两个排序的数据集:

frames = [socio_demo_sorted,UPDRS_sorted]
full_data = pd.concat(frames,axis = 1)

给出了预期的[198行x 85列]形状。 然而,做

full_data['NUMERO_CENTRE_2']

返回原始(未排序)UPDRS 数据:

0      3
1      4
2      2
3      1
4      5
      ..
193    1
194    1
195    1
196    1
197    1
Name: NUMERO_CENTRE_2, Length: 198, dtype: int64

我不明白为什么“.sort_values”函数的效果在这里丢失了。

最佳答案

原始未排序数据帧的行索引在排序后被保留(尽管它们在排序后被打乱)。连接 2 个已排序的数据帧后,连接的数据帧将根据这些原始索引重新排列。因此,返回到未排序的订单。

您可以通过使用已排序数据帧的 .reset_index(drop=True) 重置索引或直接在排序步骤中使用参数 ignore_index=True 来解决此问题:

使用其中之一:

socio_demo_sorted = socio_demo.sort_values(['NUMERO_CENTRE_1','NUMERO_INCLUSION_1']).reset_index(drop=True)
UPDRS_sorted = UPDRS.sort_values(['NUMERO_CENTRE_2','NUMERO_INCLUSION_2']).reset_index(drop=True)

或通过:

socio_demo_sorted = socio_demo.sort_values(['NUMERO_CENTRE_1','NUMERO_INCLUSION_1'], ignore_index=True)
UPDRS_sorted = UPDRS.sort_values(['NUMERO_CENTRE_2','NUMERO_INCLUSION_2'], ignore_index=True)

然后,根据您的代码进行连接:

frames = [socio_demo_sorted,UPDRS_sorted]
full_data = pd.concat(frames,axis = 1)

关于python - Pandas:concat 函数删除了数据帧的先前排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68245579/

相关文章:

python - 使用 countVectorizer 计算 Skip-gram 频率

python - 在 Django 子类中而不是在基类中强制执行唯一的外键

python - 如何将 % 添加到 numpy 数组中的每个值?

python - 随着时间的推移更新 pandas 的胜率

python - Mininet 脚本从虚拟机的 IP 而不是主机的 IP 发送流量

python - iPython 笔记本,静态交互;我错过了什么?

python - Pandas .resample() 方法 - 自定义标签?

Python 数据帧 : how can I return the number of occurrences in a column?

Python 对大型二进制字符串的按位运算

python - Python中数据的高效拆分