python - Python - 转换数据框和切片
问题描述
我附上了一个截图来帮助解释。我有一个从克利夫兰心脏数据集中提取的数据框,它需要 76 列并将它们放入 7 列,并将附加列包装到下一行。我试图弄清楚如何将该数据框转换为可读格式,如右侧数据框所示。
变量 xyz 将始终相同,但我列出的其他字母变量会有所不同。我以为我可以使用 data.loc[:, :'xyz'] 开始,但我不确定从这里去哪里:
data = pd.read_csv("../resources/cleveland.data")
data.loc[:, :'xyz']
然后,我将不得不从那里为这些变量分配列名。令人惊讶的是,一旦我解决了这个问题,训练、测试、验证部分就会变得容易得多。在此先感谢您的帮助。(我是菜鸟)
解决方案
输入数据
1 a b c
d xyz 2 e
f g h xyz
3 i j k
代码
import pandas as pd
import numpy as np
# The initial data doesn't contain header so set header to None
df = pd.read_csv("../resources/cleveland.data", header=None)
cols = df.columns.tolist()
# Reset the index to get the line number in the durty file
df = df.reset_index()
# After having melt the df, you can filter the df in order to have every values in one column.
# Those values are in the right order
df = pd.melt(df, id_vars=['index'], value_vars=cols)
df = df.sort_values(by=['index', 'variable'])
# Then you can set the line number
df['line'] = np.where(df.value == 'xyz', 1, np.nan)
df.line = df.line.cumsum()
df.line = df.line.bfill()
# If the file doesn't end with 'xyz', we have to set the line number to df.line.max() + 1
df.loc[df.line.isna(), 'line'] = df.line.max() + 1
df.line = df.line.ffill()
# We can set the column names as interger with a groupby cumsum
df['one'] = 1
df['col_name'] = df.groupby(['line'])['one'].cumsum()
df['col_name'] = "col_" + df['col_name'].astype('str')
# Then we can pivot the table
df = df[['value', 'line', 'col_name']]
df = df.pivot(index='line', columns='col_name', values='value')
print(df)
输出数据
col_name col_1 col_2 col_3 col_4 col_5 col_6
line
1.0 1 a b c d xyz
2.0 2 e f g h xyz
3.0 3 i j k NaN NaN
推荐阅读
- flutter - dart 中的 Timeline.dart 用于什么?
- c# - Google Calendar API 事件颜色
- javascript - 无法从 upvotes 部分中删除用户 ID
- debugging - Xdebug:出现某个输出时如何中断程序?
- python - 使用 Textblob-de 对德语文本进行词形还原
- css - 物化CSS的涟漪效应问题
- google-sheets - 带有计数、分组、排序功能的查询结果
- laravel - 如何处理 Laravel Passport 中的 OAuth 异常?
- react-native - 如何在 expo sdk33 中加载“ionicons”字体?
- sql - 我们可以通过过滤类别来更改小计吗?