我有 csv 数据
index username
1 ailee
2 yura
3 sony
4 lily
5 alex
6 eunji
7 hyun
8 jingo
9 kim
10 min
集群的数据帧结果:
index cluster
1 1
3 1
5 1
7 1
8 1
9 2
4 2
2 2
10 2
6 2
是否可以根据 csv 数据在 pd.dataframe 中添加用户名列?
我为此使用“DataFrame.merge”。这是代码
>>> import StringIO as sio
>>> import pandas as pd
>>> s1='''index username
1 ailee
2 yura
3 sony
4 lily
5 alex
6 eunji
7 hyun
8 jingo
9 kim
10 min'''
>>> s2 = '''index cluster
1 1
3 1
5 1
7 1
8 1
9 2
4 2
2 2
10 2
6 2'''
>>> df1=pd.read_csv(sio.StringIO(s1), index_col=0, delim_whitespace=True)
>>> df2=pd.read_csv(sio.StringIO(s2), index_col=0, delim_whitespace=True)
>>> df1
username
index
1 ailee
2 yura
3 sony
4 lily
5 alex
6 eunji
7 hyun
8 jingo
9 kim
10 min
>>> df2
cluster
index
1 1
3 1
5 1
7 1
8 1
9 2
4 2
2 2
10 2
6 2
>>> df1.merge(df2, left_index=True, right_index=True)
username cluster
index
1 ailee 1
3 sony 1
5 alex 1
7 hyun 1
8 jingo 1
9 kim 2
4 lily 2
2 yura 2
10 min 2
6 eunji 2
我是一名优秀的程序员,十分优秀!