【问题标题】:Pandas- How to save frequencies of different values in different columns line by line in a csv file (including 0 frequencies)Pandas-如何在csv文件中逐行保存不同列中不同值的频率(包括0个频率)
【发布时间】:2019-10-22 00:45:02
【问题描述】:

我有一个包含以下列感兴趣的 CSV 文件

fields = ['column_0', 'column_1', 'column_2', 'column_3', 'column_4', 'column_5', 'column_6', 'column_7', 'column_8', 'column_9']

对于这些列中的每一列,有 153 行数据,仅包含两个值:-1 或 +1

我的问题是,对于每一列,我想将每个 -1 和 +1 值的频率以逗号分隔的样式逐行保存在 CSV 文件中。当我执行以下操作时,我遇到了以下问题:

>>>df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
>>>print df['column_2'].value_counts()
     1    148
    -1      5
>>>df['column_2'].value_counts().to_csv('result.txt', index=False )

然后,当我打开 results.txt 时,我发现了以下内容

148

5

这显然是我不想要的,我希望文本文件的同一行中的值用逗号分隔(例如 148、5)。

第二个问题发生在其中一个频率为零时,

>>> print df['column_9'].value_counts()
      1    153
>>> df['column_9'].value_counts().to_csv('result.txt', index=False )

然后,当我打开 results.txt 时,我发现了以下内容

153

我也不希望这种行为,我希望看到 153, 0

所以,总而言之,我想知道如何用 Pandas 做到这一点

  1. 给定一列,将其不同值的频率保存在 csv 文件的同一行中,并用逗号分隔。例如:

148,5

  1. 如果存在频率为 0 的值,请将其放入 CSV。例如:

153,0

  1. 将这些频率值附加到同一 CSV 文件的不同行中。例如:

148,5

153,0

我可以用熊猫做到这一点吗?还是应该转移到其他 python 库?

【问题讨论】:

    标签: python pandas csv


    【解决方案1】:

    一些虚拟数据的例子:

    import pandas as pd
    
    df = pd.DataFrame({'col1': [1, 1, 1, -1, -1, -1],
                       'col2': [1, 1, 1, 1, 1, 1],
                       'col3': [-1, 1, -1, 1, -1, -1]})
    
    counts = df.apply(pd.Series.value_counts).fillna(0).T
    
    print(counts)
    

    输出:

           -1    1
    col1  3.0  3.0
    col2  0.0  6.0
    col3  4.0  2.0
    

    然后您可以将其导出到 csv。

    请参阅此答案以获取参考: How to get value counts for multiple columns at once in Pandas DataFrame?

    【讨论】:

      【解决方案2】:

      我相信你可以像这样做你想做的事

      import io
      import pandas as pd
      
      df = pd.DataFrame({'column_1': [1,-1,1], 'column_2': [1,1,1]})
      
      with io.StringIO() as stream:
          # it's easier to transpose a dataframe so that the number of rows become columns
          # .to_frame to DataFrame and .T to transpose
          df['column_1'].value_counts().to_frame().T.to_csv(stream, index=False)
      
          print(stream.getvalue()) # check the csv data
      
      

      但我会建议这样的事情,因为您必须以其他方式指定缺少预期值之一

      with io.StringIO() as stream:
          # it's easier to transpose a dataframe so that the number of rows become columns
          # .to_frame to DataFrame and .T to transpose
          counts = df[['column_1', 'column_2']].apply(lambda column: column.value_counts())
          counts = counts.fillna(0)
          counts.T.to_csv(stream, index=False)
      
          print(stream.getvalue()) # check the csv data
      
      

      【讨论】:

        【解决方案3】:

        这是一个示例,其中包含三列 c1、c2、c3 和数据框 d,它是在调用函数之前定义的。

        import pandas as pd
        import collections
        
        def wcsv(d):
            dc=[dict(collections.Counter(d[i]))  for i in d.columns]
            for i in dc:
                if -1 not in list(i.keys()):
                  i[-1]=0
                if 1 not in list(i.keys()):
                  i[1]=0
        
            w=pd.DataFrame([ list(j.values()) for j in dc],columns=['1','-1'],index=['c1','c2','c3'])
            w.to_csv("t.csv")
        
        d=pd.DataFrame([[1,1,-1],[-1,1,1],[1,1,-1],[1,1,-1]],columns=['c1','c2','c3'])
        wcsv(d)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-03
          • 1970-01-01
          • 2012-11-22
          • 1970-01-01
          相关资源
          最近更新 更多