我正在寻找如下功能:
new_df = df.fill(df.mean(), axis=1)
示例:
6 3
4 5
至:
5 4
5 4
答案 0 :(得分:1)
这是一个可能的解决方案:
import numpy as np
import pandas as pd
df = pd.DataFrame([[6, 3], [4, 5]])
result = pd.DataFrame(np.repeat(pd.DataFrame([df.mean()]).values, len(df), axis=0))
答案 1 :(得分:1)
import pandas as pd
# your input df
df = pd.DataFrame([[6, 3], [4, 5]], columns = ['col1', 'col2'])
# to get output df as you want
for col in df.columns: df[col] = df[col].mean()
#df
# col1 col2
#0 5.0 4.0
#1 5.0 4.0
答案 2 :(得分:1)
简短的答案是:
new_df = df.add(df.mean()-df, axis=1)
#new_df
# 0 1
#0 5.0 4.0
#1 5.0 4.0
答案 3 :(得分:1)
您可以应用numpy的mean
函数并广播结果:
import numpy as np
df.apply(np.mean, result_type='broadcast')