簡體   English   中英

從名稱包含特定字符串的列創建新列

[英]creating new column from columns whose name contains a specific string

對於名稱包含特定字符串Time的列,我想創建一個具有相同名稱的新列。 我希望 Pax_cols 的每一項(如果有多個)用Temp列的總和來更新列。

data={'Run_Time':[60,20,30,45,70,100],'Temp':[10,20,30,50,60,100], 'Rest_Time':[5,5,5,5,5,5]}
df=pd.DataFrame(data)

Pax_cols = [col for col in df.columns if 'Time' in col]
df[Pax_cols[0]]= df[Pax_cols[0]] + df["Temp"]

這就是我想出的,如果 Pax_cols 只有一個值,但它不起作用。

預期 output:

data={'Run_Time':[70,40,60,95,130,200],'Temp':[10,20,30,50,60,100], 'Rest_Time':[15,25,35,55,65,105]}

您可以使用:

# get columns with "Time" in the name
cols = list(df.filter(like='Time'))
# ['Run_Time', 'Rest_Time']

# add the value of df['Temp']
df[cols] = df[cols].add(df['Temp'], axis=0)

output:

   Run_Time  Temp  Rest_Time
0        70    10         15
1        40    20         25
2        60    30         35
3        95    50         55
4       130    60         65
5       200   100        105

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM