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



我有一个来自半结构化csv的具有多个输入的数据,我正试图使用一组列(超过500行(中的一个(第一个(值作为包含类似标题(另外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作为最接近包含值的列的描述。

因此,如果这个规则不适用(Ticket、D、E等(,我会得到带有新标题和列的df_dont。

由于这是我的第一个问题,我很乐意得到反馈,关于清晰、解释或任何其他积极的评论都是受欢迎的。

我还不完全清楚你想要实现什么,所以这可能会被取消:

view_cols = {col for col in df.columns if col.endswith("_View")}
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

最新更新