問題:
目標:
lists | |
---|---|
1 | [1, 2, 12, 6, ABC] |
2 | [1000, 4, z, a] |
lists | liststring | |
---|---|---|
1 | [1, 2, 12, 6, ABC] | 1,2,12,6,ABC |
2 | [1000, 4, z, a] | 1000,4,z,a |
lists | liststring | |
---|---|---|
1 | [1, 2, 12, 6, ABC] | 1, 2, 12, 6, ABC |
2 | [1000, 4, z, a] | 1000, 4, z, a |
問題:
import pandas as pd
lists={1:[[1,2,12,6,'ABC']],2:[[1000,4,'z','a']]}
#create test dataframe
df=pd.DataFrame.from_dict(lists,orient='index')
df=df.rename(columns={0:'lists'})
df
lists | |
---|---|
1 | [1, 2, 12, 6, ABC] |
2 | [1000, 4, z, a] |
# 第一種解法:
df['liststring'] = [','.join(map(str, l)) for l in df['lists']]
df
lists | liststring | |
---|---|---|
1 | [1, 2, 12, 6, ABC] | 1,2,12,6,ABC |
2 | [1000, 4, z, a] | 1000,4,z,a |
# 第二種解法:
df['liststring'] = df.lists.apply(lambda x: ', '.join([str(i) for i in x]))
df
lists | liststring | |
---|---|---|
1 | [1, 2, 12, 6, ABC] | 1, 2, 12, 6, ABC |
2 | [1000, 4, z, a] | 1000, 4, z, a |
受限於blogger本身架構與限制,本網站所有內容已遷移至新網站,網址如下: https://kuo.us.to/wordpress/
沒有留言:
張貼留言