【问题标题】:apply function to dataframe pandas将函数应用于数据框熊猫
【发布时间】:2018-04-26 07:09:30
【问题描述】:

我想将我的函数应用于数据框,但它不应该影响第一行。因为这是我的总和行。当我将函数应用于数据框时,它也会划分第一行。我正在尝试将每个值除以第一行值。

我怎样才能成功? 我还想用两位小数显示结果,比如 40,00 而不是 *40,0。

这是我的函数和数据框

  df1 = pd.DataFrame(np.array([[200,200],[40,40],[80,80],[80,80]]), columns= 
  ["Erkek","Kadin"], index=["Base","AB","C1","C2"])


  def yuzde(x):
     x = x/x[0]
     x = x*100
     return round(x,2)

  tablo = df1.apply(yuzde, axis=0)

  print(tablo)

我的输出是:

         Erkek  Kadin
   Base  100.0  100.0
   AB     20.0   20.0
   C1     40.0   40.0
   C2     40.0   40.0

但我想要这样;

         Erkek    Kadin
   Base   200     200
   AB     20.00   20.00
   C1     40.00   40.00
   C2     40.00   40.00

谢谢,

【问题讨论】:

  • 将其格式化为将正确显示的字符串
  • 我的回答有问题?
  • 实际上它解决了我的大部分问题,但关键是我需要浮点格式的它们。

标签: python-3.x pandas dataframe apply


【解决方案1】:

我建议不要使用apply,因为速度慢,最好使用带有diviloc 的矢量化解决方案:

df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100)
print (df1)
      Erkek  Kadin
Base  200.0  200.0
AB     20.0   20.0
C1     40.0   40.0
C2     40.0   40.0

如果需要更改格式是可能的,但获取strings 添加applymap:

df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100).applymap('{:,.2f}'.format)
print (df1)
      Erkek  Kadin
Base    200    200
AB    20.00  20.00
C1    40.00  40.00
C2    40.00  40.00

print (df1.applymap(type))
              Erkek          Kadin
Base  <class 'int'>  <class 'int'>
AB    <class 'str'>  <class 'str'>
C1    <class 'str'>  <class 'str'>
C2    <class 'str'>  <class 'str'>

df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100).applymap('{:,.2f}'.format)
df1 = df1.astype(str)
print (df1)
      Erkek  Kadin
Base    200    200
AB    20.00  20.00
C1    40.00  40.00
C2    40.00  40.00

print (df1.applymap(type))
              Erkek          Kadin
Base  <class 'str'>  <class 'str'>
AB    <class 'str'>  <class 'str'>
C1    <class 'str'>  <class 'str'>
C2    <class 'str'>  <class 'str'>

【讨论】:

  • @Hüseyin - 我认为如果在浮点数中需要双零 40.040.00 是不可能的。它的原因是什么?还是需要真实数据df1.iloc[1:] = df1.iloc[1:].div(df1.iloc[0]).mul(100).round(2)
  • 绝对你是对的,这是不必要的,但如果其他人想要查看表格,则希望以这种方式查看。我的意思是它只是为了一个好的观点。这很愚蠢,但也是事实。 :)
猜你喜欢
  • 2018-11-13
  • 2019-02-07
  • 2013-08-10
  • 2021-02-12
  • 1970-01-01
  • 2020-09-08
  • 2021-08-27
  • 1970-01-01
相关资源
最近更新 更多