我正在尝试使用python创建报告以填充数据。下面是一个例子。我已经使用n0 = 2
来读取pandas
来创建数据框。然后,我必须使用单元格来填充文本。
数据框:
csv
如何让python打印以下内容:
name age
0 Chris 15
1 Kim 20
2 David 18
答案 0 :(得分:2)
代码:
import pandas
data = pandas.DataFrame({'name': ['Chris', 'Kim', 'David'],
'age': [15, 20, 18]})
for index, row in data.iterrows():
print('name is {} age {}.'.format(row['name'], row['age']))
输出:
name is Chris age 15.
name is Kim age 20.
name is David age 18.
答案 1 :(得分:1)
In [12]: import pandas as pd
In [13]: df = pd.DataFrame([
...: {'name': 'Chris', 'age': 15},
...: {'name': 'Kim', 'age': 20},
...: {'name': 'David', 'age': 18}
...: ])
In [14]: df
Out[14]:
age name
0 15 Chris
1 20 Kim
2 18 David
In [15]: for name, age in zip(df['name'], df['age']):
...: # Python 3.6+
...: print(f'name is {name} age {age}')
...:
...: # Python 3.5 and below
...: # print('name is {name} age {age}'.format(**df.to_dict()))
...:
name is Chris age 15
name is Kim age 20
name is David age 18
In [16]:
答案 2 :(得分:1)
使用lambda进行迭代
import pandas
data = pandas.DataFrame({'name': ['Chris', 'Kim', 'David'],
'age': [15, 20, 18]})
def print_func(x):
print('name is {} and age is {}'.format(x['name'],x['age']))
data.apply(lambda x:print_func(x),axis=1)
输出:
name is Chris and age is 15
name is Kim and age is 20
name is David and age is 18