简体   繁体   English

从名称包含特定字符串的列创建新列

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

For the columns with name containing a specific string Time , I would like to create a new column with the same name.对于名称包含特定字符串Time的列,我想创建一个具有相同名称的新列。 I want for each item of Pax_cols (if there are more than one) to update the column with the sum with the column Temp .我希望 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"]

This is what I came up with, if Pax_cols has only one values, but it does not work.这就是我想出的,如果 Pax_cols 只有一个值,但它不起作用。

Expected output:预期 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]}

You can use:您可以使用:

# 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: 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.

相关问题 从 Pandas DataFrame 中删除名称包含特定字符串的列 - Drop columns whose name contains a specific string from pandas DataFrame 查找名称包含特定字符串的列 - Find column whose name contains a specific string 从 pandas DataFrame 中删除名称包含特定字符串的第一个(或任何第 n 个)列 - Drop the first (or any nth) column whose name contains a specific string from pandas DataFrame 查找名称包含固定列中特定值的列 - Find column whose name contains a specific value that is in a fixed column 如果列包含 Python 中的特定字符串,则从列中删除值 - Remove values from columns if a column contains specific string in Python 从列名包含特定字符串的数据框中创建列表 - creating list from dataframe where column name contains particular string 寻求更好的解决方案以创建包含现有列中特定单词的新列 - Asking for better solution for creating a new column that contains specific word in existing columns 将函数应用于列标题包含特定字符串的数据框中的列 - Applying a function to columns in a dataframe whose column headings contain a specific string 从pandas中的单个字符串列创建新的二进制列 - Creating new binary columns from single string column in pandas 如果 DataFrame 包含特定字符串,则创建新列 - Create new column if DataFrame contains specific string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM