首页 > 解决方案 > 如何将数据框中的行作为字符串检索?

问题描述

我可能对你们有愚蠢的问题,但到目前为止我找不到解决问题的有效方法。我有一个通过自动输入提供的数据框,我正在转换这些数据(与我的问题并不真正相关):

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

我怎样才能简单地访问我的单元格中的数据并将其格式化为字符串格式?

谢谢!

标签: pythonpandasdataframe

解决方案


之后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()将删除字符串之前或之后的任何空格。


推荐阅读