简体   繁体   中英

Is there a more concise way of taking the mean of multiple variables based on a specific sub-string from a string

I have variables associated with a name that i want to take the mean of, based on its MainName. Noting that i have more than two MainNames as opposed to the example below, and would look messy doing all of it. So i was wondering if anyone could make this more concise? Thanks in advance!

fullname = ['MainName1,subname1','MainName1,subname2','MainName2,subname1','MainName2,subname2']
var1 = [1,5,9,4]
var2 = [2,6,1,5]
var3 = [3,7,2,6]
var4 = [4,8,3,7]

    vars = pd.DataFrame(np.column_stack([fullname,var1,var2,var3,var4]))
    vars = vars.set_index('fullname')

    meanvars = [(allvars[allvars.index.str.contains('MainName1')]).mean(),
                (allvars[allvars.index.str.contains('MainName2')]).mean()]
    MainName = ['MainName1','MainName2']

    Final = pd.DataFrame(np.column_stack([MainName,meanvars]))

You can use str.extract for get substrings with joined substrings from list joined by | for regex OR passed to groupby with aggregating mean :

fullname = ['MainName1,subname1','MainName1,subname2',
            'MainName2,subname1','MainName2,subname2']
var1 = [1,5,9,4]
var2 = [2,6,1,5]
var3 = [3,7,2,6]
var4 = [4,8,3,7]

df = pd.DataFrame(np.column_stack([var1,var2,var3,var4]), index=fullname)
print (df)
                    0  1  2  3
MainName1,subname1  1  2  3  4
MainName1,subname2  5  6  7  8
MainName2,subname1  9  1  2  3
MainName2,subname2  4  5  6  7

L = ['MainName1','MainName2']
idx = df.index.str.extract('('+ '|'.join(L) + ')', expand=False)
print (idx)
Index(['MainName1', 'MainName1', 'MainName2', 'MainName2'], dtype='object')

df = df.groupby(idx).mean()
print (df)
             0    1    2    3
MainName1  3.0  4.0  5.0  6.0
MainName2  6.5  3.0  4.0  5.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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