繁体   English   中英

Pandas:如何将列中的一个值(值重复自身)用作另一列中的 header,多次使用通配符

[英]Pandas : How to use one value from a column (value repeats itself) as a header from another column, multiple times using wildcards

我有一个来自半结构化 csv 的多个输入的数据,我正在尝试使用一组列(超过 500 个)中的一个(第一个)值作为 header 用于包含类似标题的其他列集(另外 500 行)

读完后我得到了这样的东西

import pandas as pd, numpy as np

df = pd.DataFrame({'Service': np.arange(8),
               'Ticket': np.random.rand(8),
               'Var_1': np.random.rand(8), # values column
               'Var_1_View': 'temp temp temp temp temp temp temp temp'.split(), # header of values of column
               'Var_2': np.arange(8), 
               'Var_2_View': 'pres pres pres pres pres pres pres pres'.split(),
               'Var_3': np.arange(8) * 2,
               'Var_3_View': 'shift shift shift shift shift shift shift shift'.split(),
               'D': np.arange(8) * 5,
               'Mess_3': np.random.rand(8),
               'Mess_3_View': 'id id id id id id id id'.split(),
               'E': np.arange(8)})

包含值的标题最多以 3 位数字 _# 到 _### 结尾(准确地说是 500 以上)。 带有关于值的描述的标题以文本结尾:_View

我创建了两个 dfs,一个包含,另一个不包含表达式 _View

df_headers =df.iloc[:,df.columns.str.contains('View')] # wanted headers on columns containing values
df_values =df.iloc[:,~df.columns.str.contains('View')] # headers should be replaced here

我的想法是从 df_headers 中提取第一个值作为列表并使用 df.replace 或 df.rename,更改包含值的 df_values 上的标题。

我可以手动完成,但我有一个带有不同前缀和后缀的巨大 df,但总是使用 _View 作为包含值的最近列的描述。

结果,我将拥有带有新标题和列的 df_dont,此规则不适用(票证、D、E 等)。

自从这是我的第一个问题以来,我很高兴收到关于清晰度、解释或任何其他积极评论的反馈。

我并不完全清楚你想要实现什么,所以这可能会关闭:

view_cols = {col for col in df.columns if "_View" in col}
rename_dict = {
    col.replace("_View", ""): df[col].iat[0] for col in view_cols
}
new_cols = [col for col in df.columns if col not in view_cols]
df_new = df[new_cols].rename(columns=rename_dict)

结果:

   Service    Ticket      temp  pres  shift   D        id  E
0        0  0.623941  0.934402     0      0   0  0.644999  0
1        1  0.122866  0.918892     1      2   5  0.675976  1
2        2  0.472081  0.790443     2      4  10  0.825020  2
3        3  0.914086  0.849609     3      6  15  0.357074  3
4        4  0.684477  0.729126     4      8  20  0.010928  4
5        5  0.132002  0.673680     5     10  25  0.884599  5
6        6  0.841921  0.224638     6     12  30  0.197387  6
7        7  0.721800  0.412439     7     14  35  0.875199  7

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM