![](/img/trans.png)
[英]How do I create a dictionary from a Pandas dataframe with a specific format
[英]How to create a text file of a specific format from Pandas Dataframe
概述:我有一個帶有 6 列的 Pandas Dataframe,並且需要在文本文件中使用 Output,如下所示。
輸入:
文本文件中需要 output,如下所示:
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
這可以通過編寫 function 將每一行轉換為字符串,然后使用 DataFrame.apply 將其應用於DataFrame.apply
的行來有效地完成。 關鍵字參數axis=1
指定 function 應應用於行,而不是列。
轉換本身包括弄清楚它是哪種比較,然后用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.