python - 以可以在 Python 中排序的格式存储输出

标签 python python-3.x pandas

我正在努力学习 Python,并尝试获取存储在文件中的列表(以逗号分隔)并将其转换为可以使用 Python 排序的数据存储,每四个字符串填充一行。例如,如果我在文件中有以下内容:

'apples are great'
,'neg': 0.485, 'neu': 0.392, 'pos': 0.123, 'compound': -0.812,
'crayons are waxy'
,'neg': 0.302, 'neu': 0.698, 'pos': 0.0, 'compound': -0.3818,
'a happy girl'

,'neg': 0.0, 'neu': 1.0, 'pos': 0.0, 'compound': 0.0,
'a phone is alive' 
,'neg': 0.0, 'neu': 0.737, 'pos': 0.263, 'compound': 0.3612,..........

我想要一个具有以下内容的数据框:

Subject           Neg    Neu    Pos    Compound 
apples are great  0.485  0.392  0.123  -0.812 
crayons are waxy  0.302  0.698  0.0    -0.3818 
a happy girl      0.0    1.0    0.0    0.0 
a phone is alive  0.0    0.737  0.263  0.3612 

我的目标是按复合列排序,并查找第一列中的单词频率。 我觉得这应该相对容易,但曾尝试读入一个数据框,但它变成了一行,每个值都在一列中,然后还试图将它变成一个带有句子的文本 block ,但再次得到不正确的结果。

提前感谢您的帮助。

我尝试过的例子

test = open('Heros_toSort.txt')
test2=test.readlines()
df = pd.DataFrame(test2, columns = ['name'])
df.assign(name=df.name.str.split(','))

最佳答案

Python 有一个内置的库csv,可以用来轻松读取数据。这也可以使用标准的 i/o 工具来执行,但这就是我的解决方案。

在您的 csv 中,每行的第一个条目是引号中的名称,第二个到第五个是值,所有这些都以相同的顺序出现。这些值在名称和模式 : 之后有一个数字。我们可以去掉名字周围的引号和冒号后面的数字,然后用它来制作一个 pandas 数据框。

import csv
import pandas as pd

data = []

with open('data.csv', 'r') as in_file:
  c_reader = csv.reader(in_file, delimiter=',')
  for row in c_reader:
    this_row = []

    #from each row, get the name first, stripping the leading and trailing ' single quotes.
    this_row.append(row[0].strip().lstrip('\'').rstrip('\''))

    #get the remaining values
    for i in range(1, len(row)):

      #all values appear after a ': ' pattern, in the same order. split on ': '
      #and get the second half of the split - it's the value we're looking for
      this_row.append(row[i].split(": ",1)[1])

    #add this to the array
    data.append(this_row)

#make a dataframe out of the csv file
df = pd.DataFrame(data, columns=['Name', 'neg', 'neu', 'pos', 'compound'])
print(df)

Demo

关于python - 以可以在 Python 中排序的格式存储输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58597295/

相关文章:

python - 如何提高列表中多次追加的性能?

python - 我如何处理 pytrends 的结果?

python - Pandas 将数据框与学生成绩与历史分位数进行比较

regex - 在 pandas 的正则表达式中使用列名称

python - 在 matplotlib 动画模块中管理动态绘图

Python:如何确保函数在第一次调用时加载一次?

python - Numpy:为什么 are.mean() 比 array.sum()/array.size 慢

python - Pandas - 按任何列中的最高单个值对数据框进行排序

Python初学者--如何清理这一段代码

Python:在数组中查找一个元素,如果找不到则做某事