pandas 如何在换行符模式中添加具有自己值的另一列中的两列比率

wvt8vs2t  于 2023-11-15  发布在  其他
关注(0)|答案(3)|浏览(138)

假设我有一个DataFrame ...

data = {'Col1': [232, 348, 649], 'Col2': [1500, 1550, 1600], 'Col3': [330, 290, 668]}
df = pd.DataFrame(data)

字符串
现在我想在Col2的相应行中添加Col1和Col3与Col2的比率作为一个新行,如下所示。

Col1    Col2    Col3
232     1500     330
      (0.70)
348     1550     290
      (1.20)  
649     1600     668
      (0.97)


如何做到这一点plz?

sxpgvts3

sxpgvts31#

如果是为了视觉目的,你可以试试这个:

def ratio_of(c1, c2, at="Col2"):
    return (df[c1].div(df[c2]).map(
            lambda v: f"({v:.2f})").to_frame(at))

out = (pd.concat([
    df.astype("O"), ratio_of("Col1", "Col3")]).reset_index()
           .sort_values(["index", "Col2"], ignore_index=True)
           .drop(columns="index").fillna(""))

字符串
输出量:

print(out.to_string(index=False))

Col1   Col2 Col3
 232   1500  330
     (0.70)     
 348   1550  290
     (1.20)     
 649   1600  668
     (0.97)

zazmityj

zazmityj2#

使用字符串操作和tabulate

from tabulate import tabulate

print(tabulate(
        df.assign(Col2=df['Col2'].astype(str)+'\n('
                  +df['Col1'].div(df['Col3']).round(2).astype(str)
                  +')'),
        headers='keys', tablefmt='plain')
     )

字符串
或者:

from tabulate import tabulate

print(tabulate(
        df.assign(Col2=df.apply(lambda r: f'{r["Col2"]}\n({round(r["Col1"]/r["Col3"], 2)})', axis=1),
        headers='keys', tablefmt='plain')
     )


输出量:

Col1  Col2      Col3
 0     232  1500       330
            (0.7)
 1     348  1550       290
            (1.2)
 2     649  1600       668
            (0.97)

esyap4oy

esyap4oy3#

请创建一个列表,在for循环中添加一个新行,然后在末尾将其转换为DF。

验证码:

import pandas as pd

data = {'Col1': [232, 348, 649], 'Col2': [1500, 1550, 1600], 'Col3': [330, 290, 668]}
df = pd.DataFrame(data)

df['Ratio'] = df['Col1'] / df['Col3']
result_data = []

# add each row and new line with ratio
for index, row in df.iterrows():
    result_data.append(row)
    result_data.append(pd.Series({'Col1': '', 'Col2': f'({row["Ratio"]:.2f})', 'Col3': ''}))

result_df = pd.DataFrame(result_data)
result_df = result_df.reset_index(drop=True)
result_df = result_df.drop('Ratio', axis=1) #drop ratio

print(result_df)

字符串

输出:

Col1    Col2   Col3
0  232.0  1500.0  330.0
1         (0.70)
2  348.0  1550.0  290.0
3         (1.20)
4  649.0  1600.0  668.0
5         (0.97)

相关问题