简体   繁体   English

读取 csv Pandas 空格倍数

[英]Read csv Pandas spaces multiples

在此处输入图像描述

I have a very similar dataset in csv file with two column,我在 csv 文件中有一个非常相似的数据集,有两列,

For Example: In first row and first column Item:"Betarraga paquete 5 unidades"例如:在第一行和第一列项目:“Betarraga paquete 5 unidades”

In first row and second column qty:1在第一行和第二列数量:1

Item    qty
Betarraga paquete 5 unidades    1
Betarraga paquete 5 unidades    2
Betarraga paquete 5 unidades    1
Betarraga paquete 5 unidades    1
CANASTA PEQUEÑA 1
Cebolla Nueva 20 unidades   1
Cebolla Nueva 20 unidades   2
Cebolla Nueva 20 unidades   1
Cebollin atado de 3 2
Cebollin atado de 3 2
Cebollin atado de 3 3
Cebollin atado de 3 1
Cebollin atado de 3 1
Cebollin atado de 3 1
Cebollin atado de 3 1

II should like to read with pandas, but using:我想用 pandas 阅读,但使用:

     df1 = pd.read_csv(r'pedidos4.csv',sep='\s+',encoding='utf-8',error_bad_lines=False)  

This only returns 2 column but first word in the first column input as rowname这仅返回 2 列但第一列输入中的第一个单词作为行名

在此处输入图像描述

  df.shape
  (15, 2)

I am able to read the exact text block you have posted as 2 columns.我能够阅读您发布为 2 列的确切文本块。 Please try using sep='\s\s+'请尝试使用sep='\s\s+'

After that, you can write a function that takes in a row, checks if qty is null , fixes the qty column and the Item column and returns the row.之后,您可以编写一个 function ,它接收一行,检查qty是否为null ,修复qty列和Item列并返回该行。 Then you can apply it over the df over axis=1然后你可以将它应用到df over axis=1

Item    qty
Betarraga paquete 5 unidades    1
Betarraga paquete 5 unidades    2
Betarraga paquete 5 unidades    1
Betarraga paquete 5 unidades    1
CANASTA PEQUEÑA 1
Cebolla Nueva 20 unidades   1
Cebolla Nueva 20 unidades   2
Cebolla Nueva 20 unidades   1
Cebollin atado de 3 2
Cebollin atado de 3 2
Cebollin atado de 3 3
Cebollin atado de 3 1
Cebollin atado de 3 1
Cebollin atado de 3 1
Cebollin atado de 3 1
df = pd.read_clipboard('\s\s+')

#Then use fix to fix the qty values

def fix(row):
    if pd.isnull(row['qty']):
        row['qty']=row['Item'][-1:]
        row['Item']=row['Item'][:-1].strip()
    return row

fixed_df = df.apply(fix, axis=1)
print(fixed_df)
                            Item qty
0   Betarraga paquete 5 unidades   1
1   Betarraga paquete 5 unidades   2
2   Betarraga paquete 5 unidades   1
3   Betarraga paquete 5 unidades   1
4               CANASTA PEQUEÑA    1
5      Cebolla Nueva 20 unidades   1
6      Cebolla Nueva 20 unidades   2
7      Cebolla Nueva 20 unidades   1
8           Cebollin atado de 3    2
9           Cebollin atado de 3    2
10          Cebollin atado de 3    3
11          Cebollin atado de 3    1
12          Cebollin atado de 3    1
13          Cebollin atado de 3    1
14          Cebollin atado de 3    1

I assume you want the last element of each line to be column2, and the rest in column 1. So you may have to do it manually because the amount of whitespace is inconsistent for different rows and I do not think the standard read_csv approach is easy to make work.我假设您希望每行的最后一个元素为 column2,而 rest 在第 1 列中。因此您可能必须手动执行此操作,因为不同行的空白数量不一致,我认为标准的read_csv方法并不容易工作。 So here is an alternative所以这是一个替代方案

This is our data这是我们的数据

file = StringIO(
"""Item    qty
Betarraga paquete 5 unidades    1
Betarraga paquete 5 unidades    2
Betarraga paquete 5 unidades    1
Betarraga paquete 5 unidades    1
CANASTA PEQUEÑA 1
Cebolla Nueva 20 unidades   1
Cebolla Nueva 20 unidades   2
Cebolla Nueva 20 unidades   1
Cebollin atado de 3 2
Cebollin atado de 3 2
Cebollin atado de 3 3
Cebollin atado de 3 1
Cebollin atado de 3 1
Cebollin atado de 3 1
Cebollin atado de 3 1
""")

#If 'myfile.txt' is where this data is, you should replace the above with
# file = open('myfile.txt', 'r')

Then we read file line by line, split the line at white space, use the last token as column 2 and the rest as column1, and stick in a dataframe然后我们逐行读取file ,在空白处分割行,使用最后一个标记作为第 2 列,使用 rest 作为第 1 列,并粘贴 dataframe

col1 = []
col2 = []
for line in file:
    tokens = line.split()
    c1 = ' '.join(tokens[:-1])
    c2 = tokens[-1]
    col1.append(c1)
    col2.append(c2)

df = pd.DataFrame({col1[0] : col1[1:], col2[0] : col2[1:]})
df['qty'] = df['qty'].astype(int)
df

produces生产


    Item                            qty
--  ----------------------------  -----
 0  Betarraga paquete 5 unidades      1
 1  Betarraga paquete 5 unidades      2
 2  Betarraga paquete 5 unidades      1
 3  Betarraga paquete 5 unidades      1
 4  CANASTA PEQUEÑA                   1
 5  Cebolla Nueva 20 unidades         1
 6  Cebolla Nueva 20 unidades         2
 7  Cebolla Nueva 20 unidades         1
 8  Cebollin atado de 3               2
 9  Cebollin atado de 3               2
10  Cebollin atado de 3               3
11  Cebollin atado de 3               1
12  Cebollin atado de 3               1
13  Cebollin atado de 3               1
14  Cebollin atado de 3               1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM