假设我们有以下简化数据:
df = pd.DataFrame({'A':list('abcd'),
'B':list('efgh'),
'Data_mean':[1,2,3,4],
'Data_std':[5,6,7,8],
'Data_corr':[9,10,11,12],
'Text_one':['foo', 'bar', 'foobar', 'barfoo'],
'Text_two':['bar', 'foo', 'barfoo', 'foobar'],
'Text_three':['bar', 'bar', 'barbar', 'foofoo']})
A B Data_mean Data_std Data_corr Text_one Text_two Text_three
0 a e 1 5 9 foo bar bar
1 b f 2 6 10 bar foo bar
2 c g 3 7 11 foobar barfoo barbar
3 d h 4 8 12 barfoo foobar foofoo
我要枚举具有相同前缀的列。在这种情况下,前缀是Data, Text
。因此,预期产出将是:
A B Data_mean1 Data_std2 Data_corr3 Text_one1 Text_two2 Text_three3
0 a e 1 5 9 foo bar bar
1 b f 2 6 10 bar foo bar
2 c g 3 7 11 foobar barfoo barbar
3 d h 4 8 12 barfoo foobar foofoo
请注意枚举列。你知道吗
尝试的解决方案#1:
def enumerate_cols(dataframe, prefix):
cols = []
num = 1
for col in dataframe.columns:
if col.startswith(prefix):
cols.append(col + str(num))
num += 1
else:
cols.append(col)
return cols
enumerate_cols(df, 'Data')
['A',
'B',
'Data_mean1',
'Data_std2',
'Data_corr3',
'Text_one',
'Text_two',
'Text_three']
尝试解决方案#2:
[c+str(x+1) for x, c in enumerate([col for col in df.columns if col.startswith('Data')])]
['Data_mean1', 'Data_std2', 'Data_corr3']
问题有没有更简单的解决方法,我也看了df.filter(like='Data')
等,但这看起来也很牵强。你知道吗
XY问题
只是要确保我没有掉进XY problem。我想使用^{stubnames
列需要有一个数字作为后缀,以便能够融化数据帧。你知道吗
引用文件:
With stubnames [‘A’, ‘B’], this function expects to find one or more group of columns with format A-suffix1, A-suffix2,…, B-suffix1, B-suffix2,
pd.wide_to_long(df, stubnames=['Data', 'Text'], i=['A', 'B'], j='grp', sep='_')
这将返回一个空的数据帧。你知道吗
您还可以使用defaultdict为每个前缀创建一个计数器。你知道吗
如果前缀已知:
如果分割字符
_
不在任何数据字段中:您可以使用
rename
,例如:其思想是将具有相同前缀的列分组,并为它们建立一个cumcount。你知道吗
由于我们需要分别处理不带前缀的列,因此需要使用
GroupBy.cumcount
和np.where
分两步进行:一个更简单的解决方案是将不想添加后缀的列设置为索引。那么你可以简单地
相关问题 更多 >
编程相关推荐