我有一个文件,每行有2个元素,如下面的第n行:
1 2
2 3
3 4
4 5
1 6
2 7
1 8
我需要在python中创建一个列表。
list[1]=[2,6,8]
list[2]=[3,7]
list[3]=[4]
list[4]=[5]
我该怎么办?
答案 0 :(得分:0)
尝试
import pandas as pd
a = [[1,2], [2,3], [3,4], [4, 5], [1, 6], [2,7], [1,8]]
df = pd.DataFrame(a,columns=['b','c'])
print df
z = df.groupby(['b']).apply(lambda tdf:pd.Series(dict([[vv,tdf[vv].unique().tolist()] for vv in tdf if vv not in ['b']])))
z = z.sort_index()
print z
print z['c'][1]
print z['c'][2]
print z['c'][3]
print z['c'][4]
z['d'] = 0.000
z[['d']] = z[['d']].astype(float)
len_b = len(z.index)
z['d'] = float(len_b)
z['e'] = 1/z['d']
z = z[['c', 'e']]
z.to_csv('your output folder')
print z
有关详细信息,请参阅此答案:https://stackoverflow.com/a/24112443/2632856