读取CSV-Python [英] Reading CSV - Python
问题描述
我有一个包含一些数据的csv文件,在b列中有名称,在A列中有一些相关信息。但是,并非所有名称都有相关信息
AB
1 JOHN
2 JANE
3 jane@email.com
4电话:0800etcetc
5 ZAIN
6 MIKE
7电子邮件
8电话等
我正在尝试编写代码如果AI列中有信息,它将读取A列,希望它在B列之前打印名称,而不是打印具有该名称的信息。
我希望这是有道理的。请让我知道是否有办法。
这是我想要的输出。我感谢大家的帮助。
AB
1 John
2 JANE jane@email.com
3简电话:0800等
4 ZAIN
5 MIKE电子邮件
6 MIKE电话
使用 csv库:
因此,类似这样的东西:
以open('tmp.csv','r')作为csvfile导入csv
:
reader = csv.reader(csvfile,delimiter =',')
name = None
用于阅读器中的行:
如果row [1]:
name = row [1]
print(name)
else:
print(' '.join([name,row [0]]))
输出:
B
John
JANE
JANE jane@email.com
JANE电话:foo
ZAIN
MIKE
MIKE电子邮件
MIKE电话
我看不出一种可以通过回溯来区分的方法。
通常,如果您使用的是熊猫,则可以使用内置功能。</ p>
https://pandas.pydata.org/pandas-docs/stable/genic/pandas.read_csv.html
将熊猫作为pd
df = pd.read_csv('your_file.csv')
注意:直接读取或写入csv文件的错误做法。您应该使用csv库(导入csv
)或熊猫。原因是它们处理特殊字符,转义类型,提供定界符选项以及在生产环境中随时间推移发生的所有边缘情况。
I have a csv file with some data, I have names in column b and some related information in column A. However not all names have related information
A B
1 JOHN
2 JANE
3 jane@email.com
4 phone:0800etcetc
5 ZAIN
6 MIKE
7 email
8 phon et etc
I am trying to write a code that will read column A if there is information in column A I want it to print the name before that in column B and than print the information with that name.
I hope it makes sense. Please let me know if there is a way of doing that.
This is the output i want. I thank you all for help.
A B
1 John
2 JANE jane@email.com
3 JANE phone:0800 etc etc
4 ZAIN
5 MIKE email
6 MIKE Phone
Use the csv library:
So, something like this:
import csv
with open('tmp.csv', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
name = None
for row in reader:
if row[1]:
name = row[1]
print(name)
else:
print(' '.join([name, row[0]]))
output:
B
John
JANE
JANE jane@email.com
JANE phone:foo
ZAIN
MIKE
MIKE email
MIKE phone
I don't see a way of distinguishing with lookback.
Usually, if you're using Pandas you could use the built in functionality.
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
import pandas as pd
df = pd.read_csv('your_file.csv')
Note: its bad practice to read/write csv files directly. You should use either the csv library (import csv
) or pandas. The reason for this is that they handle special characters, escape types, provide delimiter options and all of the edge cases that happen in a production environment over time.
这篇关于读取CSV-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!