假设我有两个DataFrame df1和df2,df1中的连接键是一列,但df2中的键是索引.
df1
Out[88]:
A B C
0 1 A 10
1 2 B 20
2 3 C 30
3 4 D 40
4 5 E 50
df2
Out[89]:
D E
A 22 2
B 33 3
C 44 4
D 55 5
E 66 6
Run Code Online (Sandbox Code Playgroud)
我想做点什么,
pd.merge(df1,df2, how= 'outer',left_on="B" , right_on= df2.index )
Run Code Online (Sandbox Code Playgroud)
我知道这肯定会失败.我可以通过重置df2上的索引来解决方法,但在应用程序中我必须将其索引回来.
df2=df2.reset_index()
Run Code Online (Sandbox Code Playgroud)
我想知道是否可以轻松地将一列和一个索引连接在一起?
我想使用正则表达式禁止显示特定类型的警告。警告消息是:
C:\Anaconda3\lib\site-packages\pandas\core\indexing.py:420: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
self.obj[item] = s
Run Code Online (Sandbox Code Playgroud)
我抑制过滤器的方式:
import warnings
warnings.filterwarnings("ignore", message= ".*A value is trying to.*")
Run Code Online (Sandbox Code Playgroud)
但是,它失败了。我确实尝试将警告消息的不同部分粘贴到正则表达式中,但仍然失败。我想知道为什么。
这是输入,
df1= pd.DataFrame(np.random.randn(10,3), columns= list("ABC") )
A B C
0 0.468682 -0.136178 0.418900
1 -0.362995 -0.111931 0.433537
2 -1.194483 -0.844683 -1.022719
3 0.531893 -1.032088 -1.683009
4 2.113807 -0.450628 0.004971
5 0.141548 -0.621090 -0.135580
6 0.128670 -0.460494 -0.016550
7 -0.099141 -0.010140 -0.066042
8 1.317759 -1.522207 -0.234447
9 -0.039051 -1.395751 -0.431717
Run Code Online (Sandbox Code Playgroud)
然后我创建了它的副本.我假设我实际上克隆了对象,而不只是创建一个新的链接.我希望将原始DataFrame的副本随机播放,同时保持原始DataFrame不受影响.
df2=df1.copy(deep= True)
Run Code Online (Sandbox Code Playgroud)
通过这样做,我洗了df2之后
np.random.shuffle(df2.index.values)
Run Code Online (Sandbox Code Playgroud)
然后我发现df2和df1都被洗牌了.
df1.index
Out[177]: Int64Index([7, 8, 0, 1, 3, 4, 6, 2, 5, 9], dtype='int64')
df2.index
Out[178]: Int64Index([7, 8, 0, 1, 3, 4, 6, 2, 5, 9], …Run Code Online (Sandbox Code Playgroud)