[英]How to append a list each time to a new column of a CSV file?
I have a for
loop which produces a python list
in each of it's iterations.我有一个
for
循环,它在每次迭代中生成一个 python list
。 I want to append the list
to a new column in the CSV file in each iteration of for
loop.我想在
for
循环的每次迭代中将 append list
添加到 CSV 文件中的新列。 The CSV file should be created at the time of writing the first list
to it. CSV 文件应在写入第一个
list
时创建。
The code producing the lists is similar to this code:生成列表的代码类似于以下代码:
for a in range(1,10):
b = list(range(1,a+1))
print(b)
After the first iteration of the for
loop, the CSV file should contain the first list and so on.在
for
循环的第一次迭代之后,CSV 文件应该包含第一个列表,依此类推。 The CSV file after three iterations of the for
loop should be similar to this. for
循环3次迭代后的CSV文件应该与此类似。
col1 col2 col3
1 1 1
2 2 2
3 3 3
4 4
5
I don't necessarily want the headers for the columns.我不一定想要列的标题。 Thank You All...
谢谢你们...
This might help you:这可能会帮助您:
import pandas as pd
for a in range(1,10):
b = list(range(1,a+1))
if a==1:
df = pd.DataFrame({a:b})
else:
df = df.merge(pd.DataFrame({a:b}), how='outer', left_index=True, right_index=True)
When you print the df you'll get this:当你打印 df 你会得到这个:
1 2 3 4 5 6 7 8 9
0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1
1 NaN 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2
2 NaN NaN 3.0 3.0 3.0 3.0 3.0 3.0 3
3 NaN NaN NaN 4.0 4.0 4.0 4.0 4.0 4
4 NaN NaN NaN NaN 5.0 5.0 5.0 5.0 5
5 NaN NaN NaN NaN NaN 6.0 6.0 6.0 6
6 NaN NaN NaN NaN NaN NaN 7.0 7.0 7
7 NaN NaN NaN NaN NaN NaN NaN 8.0 8
8 NaN NaN NaN NaN NaN NaN NaN NaN 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.