如何使用python pandas从csv文件中填充多行数组

问题描述 投票:0回答:1

我正在使用pandas导入CSV文件,

CSV列标题 - 年份,模型,修剪,结果

来自csv文件的值如下 -

Year  |  Model  | Trim  | Result

2012  | Camry   | SR5   | 1
2014  | Tacoma  | SR5   | 1
2014  | Camry   | XLE   | 0
etc..

数据集中有2500多行,包含200多个唯一模型。

然后将所有值转换为数值以用于分析目的。

这里的输入是csv文件的前3列,输出是第四个结果列

这是我的脚本:

import pandas as pd
inmport numpy as np

c1 = []
c2 = []
c3 = []
input = []
output = []

# read in the csv file containing 4 columns
df = pd.read_csv('success.csv')
df.convert_objects(convert_numeric=True)
df.fillna(0, inplace=True)

# convert string values to numerical values
def handle_non_numerical_data(df):
    columns = df.columns.values

    for column in columns:
        text_digit_vals = {}
        def convert_to_int(val):
            return text_digit_vals[val]
        if df[column].dtype != np.int64 and df[column].dtype != np.float64:
            column_contents = df[column].values.tolist()
            unique_elements = set(column_contents)
            x = 0
            for unique in unique_elements:
                if unique not in text_digit_vals:
                    text_digit_vals[unique] = x
                    x+=1

            df[column] = list(map(convert_to_int, df[column]))

    return df

df = handle_non_numerical_data(df)

# extract each column to insert into input array later
c1.append(df['Year'])
c2.append(df['Model'])
c3.append(df['Trim'])

#create input array containg the first 3 rows of the csv file
input = np.stack_column(c1,c2,c3)
output.append(df['Result'])

这个工作正常,除了只附加1个值,我会使用扩展,因为它似乎会将它附加到数组的末尾?

UPDATE

基本上所有这一切都很好,我的问题是创建输入数组,我希望数组由3列组成 - 年,模型,修剪。

input = ([['Year'], ['Model'], ['Trim']],[['Year'], ['Model'], ['Trim']]...)

我似乎只能在另一个上面添加一个值,而不是让它们序列化。

我现在得到什么 -

input = ([['Year'], ['Year'], ['Year']].., [['Model'], ['Model'], ['Model']]..[['Trim'], ['Trim'], ['Trim']]...) 
python arrays csv pandas
1个回答
2
投票

要详细说明我的评论,假设您有一些由非整数值组成的DataFrame:

>>> df = pd.DataFrame([[np.random.choice(list('abcdefghijklmnop')) for _ in range(3)] for _ in range(10)])
>>> df
   0  1  2
0  j  p  j
1  d  g  b
2  n  m  f
3  o  b  j
4  h  c  a
5  p  m  n
6  c  c  l
7  o  d  e
8  b  g  h
9  h  o  k

还有一个输出:

>>> df['output'] = np.random.randint(0,2,10)
>>> df
   0  1  2  output
0  j  p  j       0
1  d  g  b       0
2  n  m  f       1
3  o  b  j       1
4  h  c  a       1
5  p  m  n       0
6  c  c  l       1
7  o  d  e       0
8  b  g  h       1
9  h  o  k       0

要将所有字符串值转换为整数,请将np.uniquereturn_inverse=True一起使用,此反转将是您需要的数组,请记住,您需要重新整形(因为np.unique会将其展平):

>>> unique, inverse  = np.unique(df.iloc[:,:3].values, return_inverse=True)
>>> unique
array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n',
       'o', 'p'], dtype=object)
>>> inverse
array([ 8, 14,  8,  3,  6,  1, 12, 11,  5, 13,  1,  8,  7,  2,  0, 14, 11,
       12,  2,  2, 10, 13,  3,  4,  1,  6,  7,  7, 13,  9])
>>> input = inverse.reshape(df.shape[0], df.shape[1] - 1)
>>> input
array([[ 8, 14,  8],
       [ 3,  6,  1],
       [12, 11,  5],
       [13,  1,  8],
       [ 7,  2,  0],
       [14, 11, 12],
       [ 2,  2, 10],
       [13,  3,  4],
       [ 1,  6,  7],
       [ 7, 13,  9]])

你可以随时回去:

>>> unique[input]
array([['j', 'p', 'j'],
       ['d', 'g', 'b'],
       ['n', 'm', 'f'],
       ['o', 'b', 'j'],
       ['h', 'c', 'a'],
       ['p', 'm', 'n'],
       ['c', 'c', 'l'],
       ['o', 'd', 'e'],
       ['b', 'g', 'h'],
       ['h', 'o', 'k']], dtype=object)

要获得输出的数组,再次,您只需使用.valuesdf取适当的列 - 因为这些已经是numpy数组!

>>> output = df['output'].values
>>> output
array([0, 0, 1, 1, 1, 0, 1, 0, 1, 0])

您可能想要重塑它,具体取决于您将用于分析的库(sklearn,scipy等):

>>> output.reshape(output.size, 1)
array([[0],
       [0],
       [1],
       [1],
       [1],
       [0],
       [1],
       [0],
       [1],
       [0]])
© www.soinside.com 2019 - 2024. All rights reserved.