【问题标题】:I need to change some rows to columns from a CSV imported to Python. The CSV has Subheadings我需要将一些行从导入到 Python 的 CSV 更改为列。 CSV 有副标题
【发布时间】:2021-12-15 09:35:31
【问题描述】:

这是我导入python的原始CSV数据

BNS M1 M2 M3 M1 M2 M3
Creditor GWP GWP GWP Inf Inf Inf
Single Prem 100 200 300 600 900 50
Double Prem 200 300 400 330 100 44
Non Creditor
Rent 33 44 12 75 111 799
Spouse 90 80 86 100 10 100

有没有办法得到这样的:

Product Months Category Value
Single Prem M1 GWP 100
Single Prem M2 GWP 200
Single Prem M3 GWP 300
Single Prem M1 Inf 600
Single Prem M2 Inf 900
Single Prem M3 Inf 50
Double Prem M1 GWP 200
Double Prem M2 GWP 300
Double Prem M3 GWP 400
Double Prem M1 INF 330
Double Prem M2 INF 100
Double Prem M3 INF 44

我在使用方面取得了一些进展

df.columns = df.columns.str.extract('(\d+)', expand=False)
df = df.stack().reset_index(name='M').rename(columns={'level_3':'R_no'})

但还是很远

【问题讨论】:

  • 如果您以纯文本形式发布(样本)原始 csv,我们或许可以为您提供帮助。
  • 您好,感谢您的快速回复,我对其进行了编辑并将其更改为纯文本。真的希望这有助于再次感谢

标签: python csv pivot transpose


【解决方案1】:

我已将您的第一个表添加到名为“TestCSV.csv”的 csv 文件中。下面的代码正在生成所需的输出,您可以根据需要删除不需要的列。

from ast import If
import pandas as pd
from pandas.core.frame import DataFrame

import csv 

df = pd.read_csv('TestCSV.csv')
print(df.to_string()) 
#print(df.columns)
df = df.drop(0)
df = df.melt(id_vars = ['Product'], var_name = 'Months', value_name = 'Value')
df['Group'] = (
     df.apply(lambda x: 'GWP' if (x.Months == 'M1' or x.Months == 'M2' or x.Months == 'M3') else 'inf', axis=1)
     )
df['NewMonths'] = (
     df.apply(lambda x: x.Months[0:2] if (x.Months == 'M1.1' or x.Months == 'M2.1' or x.Months == 'M3.1') else x.Months, axis=1)
     )
print('\n')
print('Desired output....')
print('\n')
print(df)   

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
相关资源
最近更新 更多