繁体   English   中英

如何在熊猫数据框中一次将一个列表添加到一个单元格

[英]How to add one list to one cell at a time in a pandas dataframe

我有一个 for 循环,它为每次迭代打印一个十六进制字符串列表

for i in range(0, 10): print([str(hex(i))[::2], str(hex(i*10))[::2], str(hex(i+10))[::2]])

输出是

['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']

我想一次将列表读入一个单元格,这样数据框应该看起来像这样

身份证 NEWCOL
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']

你能试试这个吗:

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')

输出

   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 函数已经返回一个整数的字符串表示,不需要另外str 这是简单的一行:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM