python-3.x - 将 DataFrame 列转换为对列表
问题描述
col_1
A 2
B 8
C 4
D 3
E 1
我想把它转换成类似的东西:
[[1,2],[3,4],...]
我尝试了一个 for 循环
def get_pair(col):
lst = sorted(list(col))
pairs = []
for i in range(len(col)):
for j in range(i+1, len(lst)):
pair = [lst[i], lst[j]]
pairs.append(pair)
return pairs
在 Pandas 中有没有一种有效的方法来做到这一点?
解决方案
偶数或奇数项目的解决方案;使用 numpy
扩展@sammywemmy 提供的绝妙想法,我正在使用 numpy。以下解决方案将处理偶数或奇数:
import pandas as pd
import numpy as np
df = pd.DataFrame({'col_1':[1,2,3,4,5,6,7,8,9]})
#check length of df. If len is odd, get items upto n-1
x = len(df)
y = x if x%2 == 0 else x-1
#reshape only n-1 items if n is odd
z = np.reshape(df.col_1.to_numpy()[:y], (-1, 2)).tolist()
#if n is odd, then append nth item with None.
if x != y: z.append([df.values.tolist()[-1][0],None])
#print result
print (z)
输出将是:
[[1, 2], [3, 4], [5, 6], [7, 8], [9, None]]
如果您希望结果集如下所示:
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
然后将z.append
行更改为
if x != y: z.append(df.values.tolist()[-1])
如果列表是偶数项的解决方案
假设您的 DataFrame 是一个偶数列表,您可以使用iterrows()
并list comprehension
获得您想要的。
import pandas as pd
df = pd.DataFrame({'col_1':[1,2,3,4,5,6,7,8]})
print (df)
a = [[v['col_1'],df.iloc[i+1]['col_1']] for i,v in df.iloc[::2].iterrows()]
print (a)
这会给你:
[[1, 2], [3, 4], [5, 6], [7, 8]]
推荐阅读
- r - 如果开始和结束时间可用,R 每天汇总数据
- javascript - export default 和 export { default } 的区别
- javascript - 如何使用 vuejs 显示谷歌地图
- python - 将自然语言查询转换为 SQL 查询的任务
- android - Google Play - 确认订阅的购买令牌时出现错误“subscriptionNotOwnedByUser”
- java - com.fasterxml.jackson.databind.exc.InvalidDefinitionException:没有为 ObjectReader 配置值类型
- c# - 如何正确嵌入
- java - API 需要 2 分钟来加载数据。想用缓存
- qt - 如何创建自己的使用 qss 的 qt 小部件
- python - 将 Flask 与 Matplotlib 集成失败