如何从Dataframe创建特定格式的文本文件

2024-05-18 07:12:55 发布

您现在位置:Python中文网/ 问答频道 /正文

概述: 我有一个6列的Pandas数据框,输出需要在一个文本文件中,如下所示

输入:

Pandas_Input_DF

文本文件中需要输出,如下所示:

Intercept = 1.078
(DIVISION = '3' )*0.448
(DIVISION = '2' )*-0.024
(DIVISION IN ('1','4','5' ))*-0.002
(NEWLSGolfIN  IN ('1','Y' ))*0.093
('001'  LE ppseg30  LE '010' )*0.056
('011'  LE ppseg30  LE '020' )*0.043
(ppseg30 = '21' )*0.052

Tags: 数据inlepandasdivision文本文件interceptnewlsgolfin
1条回答
网友
1楼 · 发布于 2024-05-18 07:12:55

通过编写一个函数将每一行转换为字符串,然后使用^{}将其应用于数据帧的行,可以有效地实现这一点。关键字参数axis=1指定函数应应用于行,而不是列

转换本身包括找出它是什么类型的比较,然后用f-String构造字符串

def row_to_string(row_series):
    """Convert a DataFrame row to the correct string"""

    if row_series['EQVAL']:  # if EQVAL field is not empty
        return f"({row_series['VNAME']} = '{row_series['EQVAL']})*{row_series['ESTIMATE']}"
    # ... add the if statements and return statements for the other three types of comparisons yourself!

text_lines = dataframe.apply(row_to_string, axis=1)
text_lines.to_csv('text_file.txt', index=None, header=None)

相关问题 更多 >