我想使用熊猫数据框在Neo4j中显示查询的输出,并将结果写入文本文件中。
我可以显示查询,但是输出始终包含点。
from py2neo import Graph
import pandas as pd
graph = Graph(host="63.35.194.218", auth=("neo4j", "neo4j"))
bidirectional_different_SAB = graph.run('MATCH (n1)-[r1:HAS_CHILD|HAS_DESCENDANT]->(n2)-[r2:HAS_CHILD|HAS_DESCENDANT]->(n1) WHERE r1.weight = r2.weight and id(n1) > id(n2) and r1.SAB<>r2.SAB RETURN n1.prefered_name,r1.SAB, n2.prefered_name,r2.SAB, n1.id, n2.id;')
bidirectional_different_SAB = str(bidirectional_different_SAB.to_data_frame())
f= open("analysiss.txt","w+")
f.write("Display bidirectional relationships having different SAB")
f.write(bidirectional_different_SAB)
f.write("\n")
答案 0 :(得分:2)
尝试使用pandas数据框API直接写入文件。
df = bidirectional_different_SAB.to_data_frame()
df.to_csv("Display bidirectional relationships having different SAB.csv")
如果要使用repr
格式,则可以在运行其余代码之前使用set_option
修改pandas选项。
import pandas as pd
pd.set_option('display.width', 30000)
pd.set_option('display.max_columns', 1000)
pd.set_option('display.max_colwidth', 1000)
作为第三种选择,您可以将数据框转换为字符串,将其填充为每列固定宽度,然后使用pandas API将日期框保存到文件中。
import pandas as pd
def get_colwidth(col):
w_header = len(col.name) if col.name else 0
w_col = col.astype(str).str.len().max()
return max(w_header, w_col)
def to_fixed_width(df):
df_out = df.astype(str)
for c in df_out:
col = df_out[c]
width = get_width(col)
df_out[c] = col
# convert the index to str as well
ix = df_out.index
df_out = df_out.set_index(ix.str.rjust(get_width(ix)))
return df_out
df = bidirectional_different_SAB.to_data_frame()
df2 = to_fixedwidth(df)
# this uses the CSV writer to write the fixed width text file with a space as the separator
df2.to_csv("Display bidirectional relationships having different SAB.txt", sep=' ')
答案 1 :(得分:2)
您可以使用显示选项来定义df的打印方式: https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html
有关某些示例,请参见此帖子: How do I expand the output display to see more columns?