[英]Insert several new column with the values based on another columns in a Dataframe in pandas
I have a dataframe of the variable shape.我有一个可变形状的 dataframe。 There are two fixed columns at the start plus flexible number of columns that will be different for every case.
开始时有两个固定列,加上灵活数量的列,这些列对于每种情况都会有所不同。 Starting dataframe:
启动 dataframe:
A B FlexColumnA FlexColumnB
Apples Pears 0/1;23;45;67 1/1;23;45;67
Apples Apples 0/0;24;26;27 0/1;27;28;29
I need to insert a new column before every "FlexColumn" with the following rules:我需要使用以下规则在每个“FlexColumn”之前插入一个新列:
Name of a new column: "FlexColumn"+my_ending;新列的名称:“FlexColumn”+my_ending; my_ending is constant;
my_ending 是恒定的;
Values of a new column: "If a row of the flexible column contains '1/1', then 'norm'; if a row contains o/1, then insert 'half'; otherwise -'not_known' "新列的值:“如果灵活列的一行包含'1/1',则为'norm';如果一行包含o/1,则插入'half';否则-'not_known'”
A B FlexColumnA_myEnding FlexColumnA FlexColumnB_myEnding FlexColumnB
Apples Pears half 0/1;23;45;67 norm 1/1;23;45;67
Apples Apples not_known 0/0;24;26;27 half 0/1;27;28;29
How about something like this:像这样的东西怎么样:
def get_outcome(s):
if '1/1' in s:
return 'norm'
elif '0/1' in s:
return 'half'
else:
return 'not_known'
flexcols = [c for c in df.columns if 'FlexColumn' in c]
new_cols = []
for col in flexcols:
new_cols.append(df[col].apply(get_outcome).rename(col+'_myEnding'))
new_cols.append(df[col])
pd.concat([df['A'],df['B']]+new_cols,axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.