考虑下面的带有列表的数据框架示例
import pandas as pd
# Example DataFrame with lists as elements
data = {
'ColumnA': [['A', 'B', 'C'], ['D', 'E'], ['F'], ['G', 'H', 'I', 'J']],
'ColumnB': [['1', '2', '3', '4'], ['5'], ['6', '7'], ['8', '9', '10']]
}
df = pd.DataFrame(data)
----------------------------
ColumnA ColumnB
0 [A, B, C] [1, 2, 3, 4]
1 [D, E] [5]
2 [F] [6, 7]
3 [G, H, I, J] [8, 9, 10]
我想只根据第一行创建一个具有以下格式的csv文件
ColumnA,ColumnB
A,1
B,2
C,3
NaN,4
如何实现?
1条答案
按热度按时间h9vpoimq1#
只处理
df
的ith
行的代码(输入数据框)。在这种情况下,0th row
。确保使用
zip_longest()
而不是zip()
来获取输出中包含NaN的最后一行。输出:
处理df的
all rows
的代码(输入数据框)输出: