python - 如何解决熊猫中的wide_to_long错误
问题描述
为此,我使用了以下代码片段:-
df = pd.wide_to_long(df, stubnames=['manufacturing_unit_','outlet_','inventory','year'],i=['Brand','customer name','Factory'],j='drop').reset_index().drop('drop', 1)
但是我们遇到以下错误::
1) ValueError: stubname can't be identical to a column name
2) the id variables need to uniquely identify each row
解决方案
你可以像这样使用numpy concatenate
:
res = pd.DataFrame(pd.np.concatenate([df.iloc[:,[0,1,2,3,6,9,12]], df.iloc[:,[0,1,2,4,7,10,13]], df.iloc[:,[0,1,2,5,8,11,14]]]))
res.columns = ['Brand', 'customer name', 'Factory', 'manufacturing', 'outlet', 'inventory', 'year']
更新可变数量的列名(例如 1...3):
cols = [f'Brand|customer name|Factory|{x}$' for x in range(1,4)]
pd.DataFrame(pd.np.concatenate([df.filter(regex=col) for col in cols]))
推荐阅读
- reactjs - 滚动视图不适用于页面中的更多元素
- django - 使用 Django 子查询作为 FROM 表或 CTE 以便在聚合上有一个窗口?
- c# - Razor Pages:使用一个模型作为另一个模型的变量
- mysql - MYSQL:如何获得数量总和的最大值?
- android - PendingIntent.getBroadcast() 在 Android 11 中不起作用
- python - 如何将随机数添加到数组的每个值
- appium - 潜在不安全功能“adb shell”尚未启用
- python - Django 如何正确比较 django.utils.timezone.localtime 和 PostgreSQL 时间与时区?
- javascript - Oracle Apex 在交互式报告中打开列链接?
- python - 从 div 容器中查找 Xpath