[英]How to add one list to one cell at a time in a pandas dataframe
I have a for loop which prints a list of hex strings for each iteration我有一个 for 循环,它为每次迭代打印一个十六进制字符串列表
for i in range(0, 10): print([str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i+10))[::2]])
the output is输出是
['00', '00', '0a'] ['01', '0a', '0b'] ['02', '01', '0c'] ['03', '01', '0d'] ['04', '02', '0e'] ['05', '03', '0f'] ['06', '03', '01'] ['07', '04', '01'] ['08', '05', '01'] ['09', '05', '01']
I want to read the lists into one cell at a time such that the dataframe should look like this我想一次将列表读入一个单元格,这样数据框应该看起来像这样
idx身份证 NEWcoL NEWCOL 1 1个 ['00', '00', '0a'] ['00', '00', '0a'] 2 2个 ['01', '0a', '0b'] ['01', '0a', '0b'] 3 3个 ['02', '01', '0c'] ['02', '01', '0c'] 4 4个 ['03', '01', '0d'] ['03', '01', '0d'] 5 5个 ['04', '02', '0e'] ['04', '02', '0e'] 6 6个 ['05', '03', '0f'] ['05', '03', '0f'] 7 7 ['06', '03', '01'] ['06', '03', '01'] 8 8个 ['07', '04', '01'] ['07', '04', '01'] 9 9 ['08', '05', '01'] ['08', '05', '01'] 10 10 ['09', '05', '01'] ['09', '05', '01']
Can you try this:你能试试这个吗:
my_list=[]
for i in range(0, 10):
my_list.append([str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i+10))[::2]])
df=pd.DataFrame({'NEWcoL':my_list}).reset_index(names='idx')
Output :输出:
idx NEWcoL
0 0 [00, 00, 0a]
1 1 [01, 0a, 0b]
2 2 [02, 01, 0c]
3 3 [03, 01, 0d]
4 4 [04, 02, 0e]
5 5 [05, 03, 0f]
6 6 [06, 03, 01]
7 7 [07, 04, 01]
8 8 [08, 05, 01]
9 9 [09, 05, 01]
import pandas as pd
df = pd.DataFrame(index=[0], columns=['NEWcoL'])
for i in range(0, 10):
df.loc[i, 'NEWcoL']=[str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i+10))[::2]]
df.index = np.arange(1, len(df) + 1)
df.index.names = ['idx']
NEWcoL
idx
1 [00, 00, 0a]
2 [01, 0a, 0b]
3 [02, 01, 0c]
4 [03, 01, 0d]
5 [04, 02, 0e]
6 [05, 03, 0f]
7 [06, 03, 01]
8 [07, 04, 01]
9 [08, 05, 01]
10 [09, 05, 01]
hex
bulitin function already returns a string representation of an integer, no need to str
additionally. hex
bulitin 函数已经返回一个整数的字符串表示,不需要另外str
。 Here's simple one-liner:这是简单的一行:
In [362]: df = pd.DataFrame({'idx':range(1, 11), 'newcol':[[hex(i)[::2], hex(i*10)[::2], hex(i+10)[::2]] for i in range(10)]})
In [363]: df
Out[363]:
idx newcol
0 1 [00, 00, 0a]
1 2 [01, 0a, 0b]
2 3 [02, 01, 0c]
3 4 [03, 01, 0d]
4 5 [04, 02, 0e]
5 6 [05, 03, 0f]
6 7 [06, 03, 01]
7 8 [07, 04, 01]
8 9 [08, 05, 01]
9 10 [09, 05, 01]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.