python - 如何将数据框中的行作为字符串检索?
问题描述
我可能对你们有愚蠢的问题,但到目前为止我找不到解决问题的有效方法。我有一个通过自动输入提供的数据框,我正在转换这些数据(与我的问题并不真正相关):
import pandas as pd
import numpy as np
n = int(input())
matrix =[]
for n in range(n+1): # loop as long as expected # rows to be input
new_row = input() # get new row input
new_row = list(new_row.split(",")) # make it a list
matrix.append(new_row) #update the matrix
mat = pd.DataFrame(data=matrix[1:], index=None, columns=matrix[0])
mat.iloc[:,1] = pd.to_numeric(mat.iloc[:,1])
mat.iloc[:,2] = pd.to_numeric(mat.iloc[:,2])
mat.iloc[:,1] = round(mat.iloc[:,1] / mat.iloc[:,2])
mat2 = mat[['state', 'population']].head(5)
mat2['population'] = mat2['population'].astype(int)
mat2 = mat2.sort_values(by=['population'], ascending=False)
mat2 = mat2.to_string(index=False, header=False)
print(mat2)
我得到的答案等于:
New York 354
Florida 331
California 240
Illinois 217
Texas 109
格式很好等,但是我需要以字符串格式检索我的数据:
New York 354
Florida 331
California 240
Illinois 217
Texas 109
我已经尝试将代码的结尾更改为:
#mat2 = mat2.to_string(index=False, header=False)
print(mat2.iloc[1,:])
检索例如第一行,但随后控制台返回:
state Florida
population 331
Name: 2, dtype: object
我怎样才能简单地访问我的单元格中的数据并将其格式化为字符串格式?
谢谢!
解决方案
之后mat2 = mat2.to_string(index=False, header=False)
,mat2
成为一个字符串,您可以根据自己的喜好进行转换。例如,您可以这样做:
>>> lines = mat2.split('\n')
>>> without_format = [line.strip() for line in lines]
>>> without_format
['New York 354',
'Florida 331',
'California 240',
'Illinois 217',
'Texas 109']
Where.strip()
将删除字符串之前或之后的任何空格。
推荐阅读
- python - Anaconda TensorFlow 安装错误“HTTP”如何修复?
- ios - AppCenter react native ios build失败:“以下构建命令失败:CopyPlistFile”
- amazon-web-services - 如何为 Appsync 中的每个字段附加解析器并在之后查询
- python - 可重用 WebDriverWait 问题“对象没有属性‘驱动程序’”
- python - Add2LinkedList -- 给出 SyntaxError: Missing parentheses in call to 'print'
- python - 将一些参数从命令行直接传递给 matplotlib
- node.js - 如何在 sequelize 中使用 beforeBulkCreate 挂钩加密密码
- c# - 如何在 Quartz.net 中创建工作?
- basic - 大多数 8 位 BASIC 实现是哪种类型的解释器?
- r - eval 中的错误(predvars,data,env):找不到对象但是,该对象似乎确实存在