![](/img/trans.png)
[英]Pandas - matching values from a column in one dataframe to several columns in another dataframe and creating new columns from the original dataframe
[英]Insert several new column with the values based on another columns in a Dataframe in pandas
我有一個可變形狀的 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
我需要使用以下規則在每個“FlexColumn”之前插入一個新列:
新列的名稱:“FlexColumn”+my_ending; my_ending 是恆定的;
新列的值:“如果靈活列的一行包含'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
像這樣的東西怎么樣:
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.