python - 将行与不同格式的熊猫列合并
问题描述
我有一个数据框,其中有 n 个相同标题的列,例如。销售、销售 1、销售 2 等
并且数据是多条记录的行,其中一列具有 ID 并且 ID 列具有重复值。
销售列有第一行说明月份,例如销售销售 1 的一月、二月等
Sales Sales1 Sales2
Jan 2000 Feb 2000 Month 2000
2000 3000 4000
我已将 Sales 列过滤到数据框中
sales_df= df.filter(regex=('Sales*'))
现在我想将它与其他记录合并,但我想将它与 SalesMonth SalesValue 等列合并,在这些列中我将数据转换为 Jan 2000 Feb 3000 等
我追求的输出是
X Y ID SalesMonth Sales
xxx yyyy 001 Jan 2000 2000
编辑1:输入文件
ID Desc Sales Sales1 Sales2
Month Month Month
Jan 2000 Feb 2000 Month 2000
1 Desc1 10 20 30
1 Desc1 11 21 31
2 Desc2 7 Nan 0
3 Desc3 10 20 10
解决方案
您需要MultiIndex
先在列中创建,然后通过unstack
和最后重塑reset_index
:
print (df)
Sales Sales1 Sales2
0 Jan 2000 Feb 2000 Month 2000
1 2000 3000 4000
2 7000 8000 3000
#MultiIndex by first row
df.columns = [df.columns, df.iloc[0]]
#remove first row by indexing - [1:]
df = df.iloc[1:].unstack().reset_index(name='val')
df.columns = ['a','b','c','val']
print (df)
a b c val
0 Sales Jan 2000 0 2000
1 Sales Jan 2000 1 7000
2 Sales1 Feb 2000 0 3000
3 Sales1 Feb 2000 1 8000
4 Sales2 Month 2000 0 4000
5 Sales2 Month 2000 1 3000
如果输入更好,file
则使用参数:header
MultiIndex
import pandas as pd
temp=u"""Sales;Sales1;Sales2
Jan 2000;Feb 2000;Month 2000
2000;3000;4000
7000;8000;3000"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp), sep=';',header=[0,1])
print (df)
Sales Sales1 Sales2
Jan 2000 Feb 2000 Month 2000
0 2000 3000 4000
1 7000 8000 3000
print (df.columns)
MultiIndex(levels=[['Sales', 'Sales1', 'Sales2'], ['Feb 2000', 'Jan 2000', 'Month 2000']],
labels=[[0, 1, 2], [1, 0, 2]])
df = df.unstack().reset_index(name='val')
df.columns = ['a','b','c','val']
print (df)
a b c val
0 Sales Jan 2000 0 2000
1 Sales Jan 2000 1 7000
2 Sales1 Feb 2000 0 3000
3 Sales1 Feb 2000 1 8000
4 Sales2 Month 2000 0 4000
5 Sales2 Month 2000 1 3000
推荐阅读
- flutter - 在 Flutter 中,如何通过文档 ID 访问 Google Docs 文档?
- php - 如何将类添加到 wp 自定义导航
- 和元素
- delphi - 为什么两个不同的 TColor 值对应相同的显示颜色?
- excel - 将数据从一张表复制到标题匹配的另一张表
- python - Django Form:逗号分隔的十进制数字引发验证错误
- laravel - 收到错误消息:“目标类 [App\Http\Controllers\paymentController] 在服务器上托管后不存在
- python - 如何将列表转换为 numpy 数组?
- haskell - 在 Haskell 中分配值
- r - 绘制变量的第一个、第二个和第三个值的图形
- react-native - 使用钩子处理本机反应中的动态复选框