因此,假设我有一个示例DataFrame:
import pandas as pd
x = pd.DataFrame({"Name": ["A", "B", "C"], "total_1": [1, 2, 3], "total_2": [7, 8, 9], "total_3": [9, 10, 11]}
我想要做的是创建一个新的数据帧,它包含所有包含子串total
的列的中位数,并沿行执行。即,新数据帧将具有应当为[7, 8, 9]
的列。
我想如果我可以选择名称中带有total
的柱,然后沿着轴1计算中值,我就可以做到这一点,但我不确定如何进行这种选择。我不知道我会有多少这样的专栏。
发布于 2021-03-24 21:05:38
x['median']=x.filter(like='total').apply(lambda x: x.median(), axis=1)
Name total_1 total_2 total_3 median
0 A 1 7 9 7.0
1 B 2 8 10 8.0
2 C 3 9 11 9.0
发布于 2021-03-24 21:03:17
使用列表理解选择列,然后应用中值,如您所述:
cols = [col for col in x.columns if 'total' in col]
x['newcol'] = x[cols].median(axis=1)
Name total_1 total_2 total_3 newcol
0 A 1 7 9 7.0
1 B 2 8 10 8.0
2 C 3 9 11 9.0
发布于 2021-03-24 21:03:00
你的推理是正确的。下面是它的代码。
# Declare list that contains all columns that contain the string 'total'
cols = [col for col in x.columns if 'total' in col]
# Declare median as new column
x['median'] = x[cols].median(axis=1)
# Result
print(x)
Name total_1 total_2 total_3 median
0 A 1 7 9 7.0
1 B 2 8 10 8.0
2 C 3 9 11 9.0
请注意,axis=1
告诉median()
按列逐行操作。所以它在水平方向上进行操作。
https://stackoverflow.com/questions/66789271
复制相似问题