【问题标题】:Converting a specific column data in .csv to text using Python pandas使用 Python pandas 将 .csv 中的特定列数据转换为文本
【发布时间】:2017-08-11 11:20:15
【问题描述】:

我有一个如下所示的 .csv 文件,其中所有内容都是文本

col1             Col2
My name          Arghya
The Big Apple    Fruit

我可以使用 pd.read_csv(index_col=False, header=None) 读取此 csv。 如何将 Col1 中的所有三行组合成一个由句号分隔的列表。

【问题讨论】:

    标签: list csv pandas


    【解决方案1】:

    如果需要将列值转换为list:

    print (df.Col1.tolist())
    #alternative solution
    #print (list(df.Col1))
    ['This is Apple', 'I am in Mumbai', 'I like rainy day']
    

    然后join 中的 list 值 - 输出为 string

    a = '.'.join(df.Col1.tolist())
    print (a)
    This is Apple.I am in Mumbai.I like rainy day
    

    print (df)
                      0      1
    0              Col1   Col2
    1     This is Apple  Fruit
    2    I am in Mumbai  Great
    3  I like rainy day  Flood
    
    
    print (list(df.loc[:, 0]))
    #alternative
    #print (list(df[0]))
    ['Col1', 'This is Apple', 'I am in Mumbai', 'I like rainy day']
    

    【讨论】:

    • 请注意,.csv 文件中没有标头,即 Col1 和 Col2 不存在。
    • 我为它添加了解决方案。
    • 'DataFrame' 对象没有属性 'tolist' ..... 我使用的是 Python 3.5 和 Anaconda Spyder IDE。
    • 您需要选择第一列 - df.loc[:, 0]
    • TypeError: cannot do label indexing on with these indexers [0] of
    猜你喜欢
    • 2021-11-21
    • 2021-01-06
    • 2019-07-27
    • 1970-01-01
    • 2017-09-12
    • 2016-10-03
    • 2019-03-15
    • 2018-03-30
    • 2018-11-24
    相关资源
    最近更新 更多