【问题标题】:Converting a dataframe to text file in python在python中将数据框转换为文本文件
【发布时间】:2021-06-17 08:20:33
【问题描述】:

我在 csv 文件中有如下数据:

Name Text
Apple sweet fruit
Orange citrus fruit
Strawberry citrus fruit
eggplant vegetable
lemon sour

我想将其转换为文本文件,两列之间有分隔符:

Apple <EOL> sweet fruit
Orange <EOL> cirtus fruit
Strawberry <EOL> citrus fruit
eggplant <EOL> vegetable
lemon <EOL> sour

为此,我将代码编写为:

df = open("../data.csv", "r")
df = '<EOL>'.join([i for i in df])  

df = df.replace(",", " ")  

print(df)

为此,我得到如下输出:

Name Text
<EOL>Apple sweet fruit
<EOL>Orange cirtus fruit
<EOL>Strawberry citrus fruit
<EOL>eggplant vegetable
<EOL>lemon sour

我尝试使用 skipinitialspace = True.. 但这会引发错误。有什么办法可以解决这个问题?

【问题讨论】:

    标签: python csv text


    【解决方案1】:

    您可以使用pandas.Series.str.cat 来完成此任务,请考虑以下示例:

    import pandas as pd
    df = pd.DataFrame({'x':['A','B','C'],'y':['a','b','c']})
    xy = df['x'].str.cat(df['y'],sep='---')
    text = '\n'.join(xy)
    print(text)
    

    输出:

    A---a
    B---b
    C---c
    

    【讨论】:

    • TypeError: string indices must be integers 得到这个错误
    【解决方案2】:

    这是我解决问题的方法

    # Import pandas package
    
    import pandas as pd
    from collections import Counter
    import numpy as np
    import matplotlib.pyplot as plt
        
    # making data frame
    
    data = pd.read_csv('../Desktop/data.csv')
    
    data.head()
    
    print(data.columns)
        
    # Get all names 
    for col_name in data.columns:
       xy = data[col_name].str.cat(data[col_name],sep='<EOL>')
    

    【讨论】:

    • 这似乎不起作用,因为它在末尾添加了一个额外的 。它还将每一行转换为带有方括号的列表,输出中不需要。
    • 我已经更新了代码,请看看这是否适合你
    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    相关资源
    最近更新 更多